This question already has answers here:
Check that there are at least two arguments given in a bash script
(2 answers)
Closed 1 year ago.
How can I check in my script if I have at least 3 arguments, it must be something like:
if #number_of_arguments < 3
then
echo "Not enough arguments"
if [ $# -lt 3 ]; then
...
fi
In bash an alternative is to use an arithmetic expression.
if (( $# < 3 )); then
...
fi
Related
This question already has answers here:
String length of bash
(3 answers)
Closed 1 year ago.
I have two string variables that I need to compare by length inside of if. So I need to do something like this:
if [ length($string_one) != length($string_two) ]:
fi
if [[ ${#string} != ${#string_two} ]]; then
run command
fi
This question already has answers here:
Brace expansion with a Bash variable - {0..$foo}
(5 answers)
Closed 1 year ago.
Input: range 6
function range {
echo {0..$1}
echo {0..6}
if [[ $1 =~ 6 ]]
then
echo "Equal"
fi
}
Output:
{0..6}
0 1 2 3 4 5 6
Why is the output different whereas $1 and 6 is equal?
The curly-braces get expanded before $-variables are expanded, and the curly-brace range syntax simply doesn't recognize anything other than a pair of numbers with dots in between.
This question already has answers here:
Brace expansion with a Bash variable - {0..$foo}
(5 answers)
Closed 4 years ago.
I am trying to loop from 1 to n where n is from user input.
If I do:
read n
echo {1..$n}
I get this output for the input 5
{1..5}
How do I make it expand to
1 2 3 4 5
Keep it simple by trying to do it with a for loop as follows.
echo "enter number..."
read n
for((i=1;i<=n;i++)); do
echo "$i"
done
Or use seq with for loop as follows too.
echo "Enter number:"
read howmany
for i in $(seq 1 $howmany); do
echo "$i";
done
Curly braces don't support variables in bash, though eval could be used but it is evil and have loopholes, why so see this link carefully http://mywiki.wooledge.org/BashFAQ/048
This question already has answers here:
How do I iterate over a range of numbers defined by variables in Bash?
(20 answers)
Closed 4 years ago.
I want to loop over the value of an input argument, something like that
for i in {0..$1} do
echo $i
done
If i call my script: ./my.sh 2
I want
0
1
But i get
{0..2}
How can i do it ?
#!/usr/bin/env bash
last=$(("$1"-1))
for i in $(seq 0 "$last");
do echo "$i";
done
This question already has answers here:
How do I compare two string variables in an 'if' statement in Bash? [duplicate]
(12 answers)
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Closed 6 years ago.
#!/bin/bash
a=0
while ["$a" -lt 10]
do
a=`expr "$a" + 1`
echo $a
done
This is the error:
a.sh: 3: a.sh: [0: not found
you need to keep spaces around your brackets:
while [ "$a" -lt 10 ]
since bash interpretes strings; it uses spaces to separate words. When you write ["$a"; then bash reads: [0 (after $a is replaced with 0)