1
0
I'm new to shell scripting and are trying to learn the basics. I'm launching a script using the terminal such as "./scriptgoeshere.sh Argument1 Argument2".
I want the script to print some echo, "Hello World" is probably the best one to use, but I only want it to print out hello world if there are: Exactly two arguments, and those arguments have to consist solely of numbers. For example:
./scriptgoeshere.sh 1523 9643 ./scriptgoeshere.sh 7 96 Should work, however; ./scriptgoeshere.sh 594 arg Should NOT work, this is the script I have at the moment but it doesn't work, Ive tried figuring this out the entire day but cant seem to nail it, I even tried if/elif/else where I had it check if there are 2 inputs in the if part, and if they are both numbers in elif before continuing.
#!/bin/bash
if [ "$#" -eq 2 ] && [ "$@" -eq ^[0-9] ];
then
i=0
while [ $i -lt 3 ]
do
echo "Hello World!"
sleep 5
i=$((i+1))
done
else
echo "Need two arguments and only numbers will be accepted, such as ./scriptgoeshere 153 251"
fi
It blocks the hello world loop until I put in 2 arguments, but it doesnt matter if they are numbers or text, and I get an error then: "./scriptgoeshere.sh: line 2: [: ^[0-9]: integer expression expected". I get that error even if I write ./scriptgoeshere.sh 123 123 in the terminal to launch it. I prefer to not solve it by variables as I want to figure out the arguments when launching the actual script.
This is doing my head in!
This is what I started with to make it check if there are exactly 2 arguments and it works, I just wanna add a small fix to it so those 2 arguments HAS to be numbers. I don't get why it seems to be so hard.
#!/bin/bash
if [ "$#" -eq 2 ];
then
i=0
while [ $i -lt 3 ]
do
echo "Hello World!"
sleep 1
i=$((i+1))
done
else
echo "Need two argument, only numbers accepted"
fi
Edit: I solved it. I had worked so close.. I just needed to add extra [] to the number part of the if-string. Anyone knows why it needs to be written as [[ "$@" -eq ^[0-9] ]] while the first part can be written with just one [] ?
Sigh… If you keep changing your code I will never finish my answer that tries to elaborate your mistakes, reveal pitfalls and such. – Kamil Maciorowski – 2019-10-17T00:28:05.387
Haha I'm sorry! I've been working through a virtualbox and my keyboard inputs have been fucked and I haven't gotten around to fixing it yet, can't type []$@ for instance which means I've had it all copied over from the VMBox. Noticed a few things went missing and such, I updated it 23mins ago when I managed to solve it, did it previously when the code didnt copy-paste correctly.
I managed to solve it with if [ "$#" -eq 2 ] && [[ "$@" =~ ^[0-9] ]];" – Trollblod – 2019-10-17T00:41:33.923
And you even edited your comment after I read it! :/ And it says your solution is
[[ "$@" =~ ^[0-9] ]]
but the question body claims it is[[ "$@" -eq ^[0-9] ]]
. – Kamil Maciorowski – 2019-10-17T01:40:38.050