Sending an argument to a .sh file

Hi,

This is the content of a file name "test.sh":

#!/bin/bash
if [ ! -f $2 ]; then
 echo "I am Here"
fi

When runing the command:

./test.sh chair table

The echo command "I am Here" will appear only based on the second value, in other words only if the there is no file name "table" regardless if there isn't a file name "chair".. Why is that ?

B.What exactly did we done here ?. We sent an argument to a file containing shell commands ?

Did you notice the $2 that I marked in red in your script? Do you see that the test is looking for a file named by the 2nd command-line argument passed to your script?

What happens if you change the $2 to $1 and rerun your script at times when there is a file named chair and at times when there is not a file named chair ?

What do you think might happen if you changed the line in your script that is currently:

if [ ! -f $2 ]; then

to:

if [ ! -f "$1" ] && [ ! -f "$2" ]; then

or to:

if [ ! -f "$1" ] || [ ! -f "$2" ]; then

? Note that I added double quotes around each parameter expansion. With the files named in your example and the default characters specified in "$IFS", it doesn't matter. But you should always write you code to protect yourself in case an argument is passed to your script that contains <space>s, <tab>s, or <newline>s.

1 Like