Help Needed on shell script

#!/bin/sh
#Displaying every argument
while [$# -gt 0];
do
  echo Moving file $0;
  shift;
done
exit 0;

For the above script i get the below o/p when 2 arguments are passed when invoking the script

dmlFileCopy.sh: line 3: [2: command not found

Can you let me know how to rectify the error?

[ is synonymous with test - usually a soft, or a hard link, or internal command:

$ ll /bin/[
-r-xr-xr-x  2 root  wheel  63184 18 May  2009 /bin/[

$ ll /bin/test
-r-xr-xr-x  2 root  wheel  63184 18 May  2009 /bin/test

As such, you need a space after it. ] is added for balance - you need a space before that, too.

while [ $# -gt 0 ]
do
  echo Moving file "$1"
  shift
done
exit 0

$0 is the script name... $1 will be the first argument - each time - after shift, what was $2 will be $1. You should quote arguments to protect against spaces, etc. In your echo example, not an issue, but if you plan to mv the file, it's good practice to quote variables.

There's no need to add semi-colons after commands if it's the last command on the line.

1 Like

Furthermore, you can safety replace while [ $# -gt 0 ] with while [ "$1" ]

1 Like