Unix & Linux Stack Exchange
Q&A for users of Linux, FreeBSD and other Unix-like operating systems
Latest Questions
3
votes
2
answers
1278
views
Check if a number is in a range with zsh
Why is passing 0 as an argument results in a false positive (prints "True")? ``` #!/bin/zsh k="$1" if ((0 < k < 1)) then echo "True" fi ``` Note this script is called stitch_applier.sh Terminal ``` % ./stitch_applier.sh 0 True ``` This was run on a Linux system.
Why is passing 0 as an argument results in a false positive (prints "True")?
#!/bin/zsh
k="$1"
if ((0 < k < 1))
then
echo "True"
fi
Note this script is called stitch_applier.sh
Terminal
% ./stitch_applier.sh 0
True
This was run on a Linux system.
visual360
(41 rep)
Apr 20, 2021, 10:41 AM
• Last activity: Jul 7, 2025, 04:30 PM
11
votes
3
answers
9679
views
How to iterate a zero padded integer in bash?
How does one iterate a string with the form "[A-Z][0-9]*" Or for example: "A000001"? After receiving the variable I split: current_=$(mysql -h"$mysqlhost" -u"$mysqluser" -p"$PASS" "$DBNAME" -se "SELECT current_ FROM $GLOBALDB;") current_number=$(echo $current_ | grep -oh "[0-9]*") current_letter=$(e...
How does one iterate a string with the form "[A-Z][0-9]*" Or for example: "A000001"?
After receiving the variable I split:
current_=$(mysql -h"$mysqlhost" -u"$mysqluser" -p"$PASS" "$DBNAME" -se "SELECT current_ FROM $GLOBALDB;")
current_number=$(echo $current_ | grep -oh "[0-9]*")
current_letter=$(echo $current_ | grep -oh "[A-Z]*")
However when I try to add 1:
# add 1 & keep all leading zeros "000001"
next_number=$(printf %06d $(($current_number + 1)))
It counts to "000009" and rolls back over to "000000".
And I join as follows:
next_=$(echo "$current_letter$next_number")
And in regards to the Letter iteration I was thinking of using an Associated Array? Or brace expansion
{A..Z}
, but that is a whole different question.
jmunsch
(4456 rep)
Nov 18, 2014, 03:41 PM
• Last activity: Jun 27, 2025, 01:49 PM
4
votes
1
answers
244
views
using the bc calculator with obase and ibase to convert integer representation
I am using the bc calculator with `obase` and `ibase` to convert integer representation. I'm not used to it, because very basic things can be done with `$(( expresion ))` in bash, and most things that can't be done with that are prone to get more complicated in the future, and then, perl or java are...
I am using the bc calculator with
obase
and ibase
to convert integer representation.
I'm not used to it, because very basic things can be done with $(( expresion ))
in bash, and most things that can't be done with that are prone to get more complicated in the future, and then, perl or java are the tools of choice.
What I have done is
helper@gg$ echo 'obase=10; ibase=16;F;' | bc
15
helper@gg$ echo 'ibase=16; obase=10;F;' | bc
F
helper@gg$ echo 'ibase=16; obase=10;10;' | bc
10
helper@gg$ echo 'obase=10; ibase=16;10;' | bc
16
helper@gg$
and the result obviously depends on the order in which ibase and obase are given.
Naturally, I've taken a look at the bc manpage but found noting about this.
Question is: how does it work, and where can I read more about this, to avoid other pitfalls in the like of this.
Gyro Gearloose
(455 rep)
May 27, 2025, 01:03 PM
• Last activity: May 27, 2025, 01:52 PM
1
votes
5
answers
237
views
how to subtract a date in format: 'xyz/[int][int]/[int][int][int][int]' from the current date?
### Scenario I have containers which have last deploy dates in the format: month/date/year or feb/11/2024. I cant change the way they output the last deploy date. I'd like to subtract the last deploy date, from the current date and then write to a file if the last deploy date is greater than 2 month...
### Scenario
I have containers which have last deploy dates in the format:
month/date/year or feb/11/2024.
I cant change the way they output the last deploy date.
I'd like to subtract the last deploy date, from the current date and then write to a file if the last deploy date is greater than 2 months.
### Example container1-last-deploy.txt:
last deployed: jan/01/2024
I have several of these files.
The challenge is that the month is given in letters. I could use regex to get the date.
One solution I've thought of is to have the months in a dictionary like:
dict=(
['jan']=1
['feb']=2
)
But there is bound to be a better way.
Is it possible to convert the lettered month to integers?
This is for bash on macos, preferably a bash 3 solution.
Nickotine
(554 rep)
Jan 11, 2024, 07:27 AM
• Last activity: Dec 6, 2024, 08:14 PM
429
votes
17
answers
663549
views
How to do integer & float calculations, in bash or other languages/frameworks?
Using `echo "20+5"` literally produces the text "`20+5`". What command can I use to get the numeric sum, `25` in this case? Also, what's the easiest way to do it just using bash for floating point? For example, `echo $((3224/3807.0))` prints `0` :(. I am looking for answers using either the basic co...
Using
echo "20+5"
literally produces the text "20+5
".
What command can I use to get the numeric sum, 25
in this case?
Also, what's the easiest way to do it just using bash for floating
point? For example, echo $((3224/3807.0))
prints 0
:(.
I am looking for answers using either the basic command shell ('command
line') itself or through using languages that are available from the
command line.
Michael Durrant
(43563 rep)
Jun 14, 2012, 02:43 PM
• Last activity: Nov 26, 2024, 11:07 AM
2
votes
1
answers
465
views
What's the difference between '$var' and 'var' in an arithmetic expansion?
Bash accepts both these syntax: FOO=$(($BAR + 42)) and FOO=$((BAR + 42)) Which one is correct / most portable / less prone to errors? Or are both equally valid?
Bash accepts both these syntax:
FOO=$(($BAR + 42))
and
FOO=$((BAR + 42))
Which one is correct / most portable / less prone to errors? Or are both equally valid?
dr_
(32068 rep)
Aug 28, 2024, 01:08 PM
• Last activity: Aug 29, 2024, 02:54 PM
73
votes
7
answers
94037
views
How to create a sequence with leading zeroes using brace expansion
When I use the following, I get a result as expected: $ echo {8..10} 8 9 10 How can I use this brace expansion in an easy way, to get the following output? $ echo {8..10} 08 09 10 I now that this may be obtained using `seq` (didn't try), but that is not what I am looking for. Useful info may be that...
When I use the following, I get a result as expected:
$ echo {8..10}
8 9 10
How can I use this brace expansion in an easy way, to get the following output?
$ echo {8..10}
08 09 10
I now that this may be obtained using
seq
(didn't try), but that is not what I am looking for.
Useful info may be that I am restricted to this bash version. (If you have a zsh
solution, but no bash
solution, please share as well)
$ bash -version
GNU bash, version 3.2.51(1)-release (x86_64-suse-linux-gnu)
Bernhard
(12573 rep)
Jan 4, 2013, 08:41 AM
• Last activity: Jul 1, 2024, 01:52 PM
-3
votes
1
answers
152
views
How to split a number into unequal parts in Bash
Hypothetic example: There is a number that I will split into x parts (smaller numbers, in a range you see in the example). I need a way, ideally a one liner for the Linux Bash, to split a large number into unequal smaller numbers like: ```text 54773147129 / 11 = 11702658340 4215060707 8649154648 816...
Hypothetic example: There is a number that I will split into x parts (smaller numbers, in a range you see in the example).
I need a way, ideally a one liner for the Linux Bash, to split a large number into unequal smaller numbers like:
54773147129 / 11 = 11702658340 4215060707 8649154648 8166383273 7721726143 6316805625 5074147699 11938331015 7290181592 10452629111 12235301352
24335474529 / 5 = 3782894329 7991597003 2435897896 6966444910 3158640391
120358276480 / 9 = 15276312867 11090117156 8997563892 15321924738 10203261894 21007930376 17164309215 13595762399 7701093943
54773147129 / 8 = 10222423691 6997800027 4434683169 5675683553 1121059020 8522036904 4023455184 13776005581
and so on.
Consider the first example in more detail:
* The number is 54773147129 and I want to have 11 parts
* I do not want to simply divide the number by eleven, which would result in 11 equal but non-integer fractions, i.e.
**not** 54773147129 / 11 = 4979377011,73
In general, I don't want to have parts with decimals.
* I do not want to divide the number into 10 equal parts and one larger part that contains the integer division's modulus, i.e.
**not** 4979377011
4979377011
4979377011
4979377011
4979377011
4979377011
4979377011
4979377011
4979377011
4979377011
4979377019
* I want to have a result like:
11702658340
4215060707
8649154648
8166383273
7721726143
6316805625
5074147699
11938331015
7290181592
10452629111
12235301352
How to do this in Bash (ideally in a one-liner)?
user447274
(539 rep)
Jun 21, 2024, 04:56 AM
• Last activity: Jun 21, 2024, 10:20 PM
13
votes
9
answers
19730
views
How to sum time using bash?
I want to know the total amount of time that a series of processes would take in my computer to decide if I should running there or in a stronger computer. So, i am forecasting the running time of each command. The output looks like: process1 00:03:34 process2 00:00:35 process3 00:12:34 How can I su...
I want to know the total amount of time that a series of processes would take in my computer to decide if I should running there or in a stronger computer. So, i am forecasting the running time of each command. The output looks like:
process1 00:03:34
process2 00:00:35
process3 00:12:34
How can I sum the second column to obtain a total running time? I could try pipping each line through
awk '{sum += $2 } END { print sum }
but this makes no sense as the values are not natural numbers.
user101746
Feb 5, 2015, 07:45 PM
• Last activity: Apr 21, 2024, 04:29 AM
5
votes
5
answers
2173
views
How to treat numbers starting with zeroes as decimal integer
Input would be file name like following : A-B-000001-C A-B-000002-C ..... ..... A-B-999999-C All file should be sequential. I want to find missing sequential file names. For this I'm separating 6 digit sequence number using **awk** and using **grep** with regular expression to check if the file is p...
Input would be file name like following :
A-B-000001-C
A-B-000002-C
.....
.....
A-B-999999-C
All file should be sequential. I want to find missing sequential file names. For this I'm separating 6 digit sequence number using **awk** and using **grep** with regular expression to check if the file is present in the directory.
ls|grep "A-B-${sequencenumber}-.*"|wc -l
but shell script is not treating number as decimal and if I force the number to be treated as decimal using **10#$sequencenumber** then its removing preceding zeroes which is necessary for searching the file.
Is there any way around this?
Milon Corleone
(157 rep)
Jan 10, 2016, 11:05 AM
• Last activity: Jan 26, 2024, 02:14 PM
43
votes
11
answers
116849
views
How to compare two floating point number in a shell script
I want to compare two floating point numbers in a shell script. The following code is not working: #!/bin/bash min=12.45 val=10.35 if (( $val < $min )) ; then min=$val fi echo $min
I want to compare two floating point numbers in a shell script. The following code is not working:
#!/bin/bash
min=12.45
val=10.35
if (( $val < $min )) ; then
min=$val
fi
echo $min
RIchard Williams
(715 rep)
Nov 16, 2011, 12:47 PM
• Last activity: Nov 8, 2023, 02:01 PM
-1
votes
2
answers
125
views
Numeric if conditions that read a command in a bash script
I'm trying to write a command that looks at my battery state and suspends the laptop if the battery is low. I tried using something like this: ``` #!/bin/bash if [ $(acpi -b | cut -c 25) < 11 ] then notify-send "Hello" fi ``` This works, but for some reason if I replace 11 with a one-digit number li...
I'm trying to write a command that looks at my battery state and suspends the laptop if the battery is low. I tried using something like this:
#!/bin/bash
if [ $(acpi -b | cut -c 25) < 11 ]
then notify-send "Hello"
fi
This works, but for some reason if I replace 11 with a one-digit number like 5, I get an error
battery-notify-standby: line 2: 5: No such file or directory
I also tried to replace the square bracket with two round brackets to designate it as an arithmetic expression. Then I get
battery-notify-standby: line 2: ((: < 11 : syntax error: operand expected (error token is "< 11 ")
I'm not sure what exactly is going wrong. Can someone help me out?
Alexander Praehauser
(221 rep)
Oct 28, 2023, 02:51 PM
• Last activity: Oct 28, 2023, 05:10 PM
0
votes
1
answers
43
views
Logging sum of Mem and Swap from free command output
In relation to this: https://unix.stackexchange.com/a/754252/582781 Solution 1: free -g -s2 | sed -u -n 's/^Mem:\s\+[0-9]\+\s\+\([0-9]\+\)\s.\+/\1/p' >> memory.log Is there a way to add Swap to this, so that I would log the sum of used Mem and Swap?
In relation to this:
https://unix.stackexchange.com/a/754252/582781
Solution 1:
free -g -s2 | sed -u -n 's/^Mem:\s\+[0-9]\+\s\+\([0-9]\+\)\s.\+/\1/p' >> memory.log
Is there a way to add Swap to this, so that I would log the sum of used Mem and Swap?
Aleksander
(5 rep)
Oct 28, 2023, 07:10 AM
• Last activity: Oct 28, 2023, 10:49 AM
10
votes
6
answers
1599
views
Arithmetic on values with memory size units
Let’s say I have a bunch of numbers representing quantities of memory, written in the form `86k` or `320m` or `1.7g` for instance. How can I compute their sum in command line, and get back a human-readable result? Being able to compute subtractions would be nice too. The perfect tool would handle se...
Let’s say I have a bunch of numbers representing quantities of memory, written in the form
86k
or 320m
or 1.7g
for instance. How can I compute their sum in command line, and get back a human-readable result?
Being able to compute subtractions would be nice too. The perfect tool would handle several sets of notations (such as 1g
/ 1G
/ 1GB
/ 1Go
/ 1GiB
/ 1.7Gio
) and their meaning (binary or decimal multipliers).
I am looking for a pure calculator. These numbers are not necessarily the size of some files on my disk, so tools such as find
, stat
or du
are not an option.
This is obviously easy to implement (with some hurdles regarding precision), but I would be damned if this didn’t exist already!
Maëlan
(446 rep)
Oct 15, 2020, 12:42 PM
• Last activity: Oct 20, 2023, 01:34 PM
-4
votes
1
answers
104
views
How to protect variable name inside shell arithmetic?
Variables can be protected with curly braces. ```bash Mynewvar=1 echo $Mynewvar 1 echo ${Mynewvar} 1 ``` However I can no longer protect them when inside shell arithmetic. ```bash Mynewvar=1 echo $((Mynewvar+9)) 10 echo $(({Mynewvar}+9)) ``` ``` bash: {Mynewvar}+9: syntax error: operand expected (er...
Variables can be protected with curly braces.
Mynewvar=1
echo $Mynewvar
1
echo ${Mynewvar}
1
However I can no longer protect them when inside shell arithmetic.
Mynewvar=1
echo $((Mynewvar+9))
10
echo $(({Mynewvar}+9))
bash: {Mynewvar}+9: syntax error: operand expected (error token is "{Mynewvar}+9")
What is the right way to enclose variable names when it is inside shell arithmetic?
jwav629
(1 rep)
Jul 18, 2023, 05:20 PM
• Last activity: Jul 18, 2023, 06:02 PM
3
votes
4
answers
515
views
Apply arithmetic into piped command
So far I have this: sudo find /path/to/dir -type f | xargs -d "\n" sudo stat -c "%Y %n" | {arithmetic to check if %Y is between 1685518962 and 1685624474??} | {show file path} To note, I am aware of `find -newermt` but am more generally asking about performing arithmetic in the command line. To clar...
So far I have this:
sudo find /path/to/dir -type f |
xargs -d "\n" sudo stat -c "%Y %n" |
{arithmetic to check if %Y is between 1685518962 and 1685624474??} |
{show file path}
To note, I am aware of
find -newermt
but am more generally asking about performing arithmetic in the command line.
To clarify, I am hoping for a one-liner.
TCSH or BASH are acceptable to me but don't hesitate to enlighten me with another shell.
MonkeyZeus
(143 rep)
Jun 1, 2023, 01:10 PM
• Last activity: Jun 2, 2023, 07:25 PM
23
votes
3
answers
93251
views
How to round floating point numbers in shell?
How do I correctly round IEEE 754 floating point numbers on the command line? I want to specify the precision of the output number - the count of fractional digits. Rounding `6.66` to precision `1` should give `6.7`, for example. More in the table below: Value Precision Rounded 6.66 0 7 6.66 1 6.7 6...
How do I correctly round IEEE 754 floating point numbers on the command line?
I want to specify the precision of the output number - the count of fractional digits.
Rounding
6.66
to precision 1
should give 6.7
, for example. More in the table below:
Value Precision Rounded
6.66 0 7
6.66 1 6.7
6.66 2 6.66
6.66 3 6.660
6.666 3 6.666
6.6666 3 6.667
It should be usable in an interactive shell, but ideally robust enough for using it in production shell scripts.
Volker Siegel
(17703 rep)
Nov 10, 2014, 05:49 AM
• Last activity: May 5, 2023, 10:24 AM
1
votes
1
answers
322
views
Arithmetic operation issue in bash script | invalid arithmetic operator
From a bash script I am downloading a file from a server using `curl` call. Now I want to check if the file is fully downloaded. For this I am comparing the size of downloaded file and `Content-Length` header. Although both are equal I am getting below error: ")syntax error: invalid arithmetic opera...
From a bash script I am downloading a file from a server using
curl
call. Now I want to check if the file is fully downloaded. For this I am comparing the size of downloaded file and Content-Length
header. Although both are equal I am getting below error:
")syntax error: invalid arithmetic operator (error token is "
Part of bash script:
remote_size=$(curl -kI "${HEADERS[@]}" "$url" | grep -i content-length | awk '{print $2}')
local_size=$(stat --format=%s "$dest/$file")
if (( remote_size == local_size )); then
echo "File is complete" >&2
elif (( remote_size > local_size )); then
echo "Download is incomplete" >&2
elif (( remote_size &2
fi
Inspired by: https://stackoverflow.com/questions/37885503/check-if-curl-incremental-continue-at-download-is-successful/37885681?
Can anyone please let me know what is the issue here and how to resolve it?
Thanks in advance
P.S: I am testing on ubuntu (on WSL), but the script will finally be part of Linux on an embedded platform. Please let me know if any info is missing
Preeti
(223 rep)
Apr 5, 2023, 10:51 AM
• Last activity: Apr 17, 2023, 01:36 PM
-5
votes
1
answers
323
views
printing prime number in bash
hi i am new to programming and currnetly learing bash script. please help with this error " line 28: expected `)' " Given below is my program. read -p "enter the number:" a while [[ $a -le 100 ]] do echo "$a" if [[ (($a-1) % 2) -eq 0 ]] then ((a++)) fi done
hi i am new to programming and currnetly learing bash script.
please help with this error " line 28: expected `)' "
Given below is my program.
read -p "enter the number:" a
while [[ $a -le 100 ]]
do
echo "$a"
if [[ (($a-1) % 2) -eq 0 ]]
then
((a++))
fi
done
KNIGHTSS
(1 rep)
Mar 19, 2023, 05:33 PM
• Last activity: Mar 19, 2023, 08:33 PM
1
votes
3
answers
591
views
Date, arithmetic, and ternary operator in one line
I have a simple code to ensure a script takes at least x seconds (500 here) on Ubuntu t1=$(date +%s) # script is here t2=$(date +%s) let "t = 500 - $t2 + $t1" (( t = t>0 ? t : 1 )) sleep $t The code works perfectly, but I believe my coding is not efficient, and these three lines t2=$(date +%s) let "...
I have a simple code to ensure a script takes at least x seconds (500 here) on Ubuntu
t1=$(date +%s)
# script is here
t2=$(date +%s)
let "t = 500 - $t2 + $t1"
(( t = t>0 ? t : 1 ))
sleep $t
The code works perfectly, but I believe my coding is not efficient, and these three lines
t2=$(date +%s)
let "t = 500 - $t2 + $t1"
(( t = t>0 ? t : 1 ))
should be expressed in one single line. My question is how to improve the code.
Googlebot
(2009 rep)
Feb 4, 2019, 09:42 PM
• Last activity: Mar 14, 2023, 12:34 PM
Showing page 1 of 20 total questions