Bash Scripting leave 4 digit numbers alone
EDIT: SOLVED. Thank you everyone!
I am building a shell script and I am stuck with comparing. I call it via ./myscript 1000, where 1000 is 开发者_运维技巧in a variable called y.
The problem is I need to make it so if I pass any 4 digit number to my script such as 0001 it will not be modified by my if statements, but when I call my script it is basically telling me 0001 and 1 are the same things. How can I check the size of $y to fix my problem?
I've tried echoing y, it does show 0001 and 1 when I pass them to my script but I do not know how to have any 4 digit number left alone.
####CODE SNIPP
#NOT EVEN NEEDED, JUST FOR SHOW, need to think of 0000 to any 4 digit #
#as different, but not sure how to do it.
if [ "$y" -ge 0000 ] && [ "$y" -le 9999 ]
then
#DO NOTHING
#IF Y <= 50 && Y >= 0
elif [ "$y" -le 50 ] && [ "$y" -ge 0 ]
then
#DO SOMETHING
#IF Y > 50 && Y <= 99
elif [ "$y" -gt 50 ] && [ "$y" -le 99 ]
then
#DO SOMETHING
fi
Does anyone have any tips on how I can tell me script 0001 and 1 are two different things? I figure bash must have something to check the input length or something but I cannot find anything.
Bash supports finding the length of a string stored in a variable.
A=hello
echo ${#A} # outputs "5"
You can use this within an if statement:
A=0001
if [ ${#A} -ne 4 ]; then
# stuff done if not four digits
fi
Note that bash will treat any arguments to -eq, -ne, -lt, -le, -gt or -ge as numbers.
If you want to treat them as a string, use = and !=
$ test 1 = 2; echo $?
1
$ test 1 = 1; echo $?
0
$ test 1 = 001; echo $?
1
$
Note how 1 and 001 are considered distinct. May this help you on your way.
If you really want to know long something is, try using wc
?
$ echo -n abc | wc -c
3
$ y=0001
$ echo -n $y | wc -c
4
$ test `echo -n $y | wc -c` -eq 4; echo $?
0
$ y=1
$ test `echo -n $y | wc -c` -eq 4; echo $?
1
$
The last case returns 1
informing us that $y
is not 4 characters long.
I'd identify the 4-digit numbers using case
:
case $y in
([0-9][0-9][0-9][0-9])
is_4_digits=yes;;
(*) is_4_digits=no;;
esac
What else you do depends on your requirements - it could be that you do everything in the '(*)
' clause; I'd use ': OK
' in the 4-digit case to indicate that this case is OK:
case $y in
([0-9][0-9][0-9][0-9]) : OK;;
(*) # ... do all the other work here ...
;;
esac
精彩评论