I have a shell script as below:
$ cat check.sh
echo "$#"
for i in "$#"; do
echo "$i"
done
If I run the script with command line args, it prints as below:
$ ./check.sh arg1 arg2 "This is a message" arg4
arg1 arg2 This is a message arg4
arg1
arg2
This is a message
arg4
All is well till now.. -- the number of arguments shown are 4
If I take $# into an variable and do the same thing on it, it will behave as below:
$ cat check.sh
VARGS="$#"
echo "$VARGS"
for i in $VARGS; do
echo "$i"
done
$ ./check.sh arg1 arg2 "This is a message" arg4
arg1 arg2 This is a message arg4
arg1
arg2
This
is
a
message
arg4
Here the number of arguments are 7.
The reason that I have taken the arguments in a temp variable is to remove some unwanted args from it and pass it to another application/process.
Can someone let me know how to get the same behavior in this scenario as if we are using "$#"
Thanks for your help in advance.
I'm using ksh93 for this, but it ought to work in ksh88 as well as it also has arrays:
set -A VARGS "$#"
IFS=
for i in ${VARGS[#]}; do
echo "$i"
done
Setting IFS= is necessary, otherwise the "This is a message" string would be chopped up on spaces.
Related
I have a script that takes in several arguments.
I need everything but $1 and $2 in a string.
I have tried this:
message="$*"
words= $(grep -v "$2"|"$3" $message)
but it doesn't work, it gives me the error:
./backup: line 26: First: command not found
Use shift 2 to shift the arguments along (it drops the first n arguments).
If you need "$1" and "$2" for later, save them in variables first.
Note that in shell, assignments to variables cannot have whitespace either side of the =.
First=$1
Second=$2
shift 2
Message=$#
Maybe something like this?
[root#tsekmanrhel771 ~]# cat ./skip1st2.sh
#!/bin/bash
COUNT=0
for ARG in "$#"
do
COUNT=$[COUNT + 1]
if [ ${COUNT} -gt 2 ]; then
RESULT="${RESULT} ${ARG}"
fi
done
echo ${RESULT}
[root#tsekmanrhel771 ~]# ./skip1st2.sh first second third 4 5 6 7
third 4 5 6 7
You can use a subarray:
$ set -- arg1 arg2 arg3 arg4
$ str=${*:3}
$ echo "$str"
arg3 arg4
More often than not, it's good practice to preserve the arguments as separate elements, though, which you can do by using $# and assigning to a new array:
$ arr=("${#:3}")
$ declare -p arr
declare -a arr=([0]="arg3" [1]="arg4")
Notice that in str=${*:3}, quoting isn't necessary, but in arr=("${#:3}"), it is (or the arguments would be split on whitespace).
As for your error message: your command
words= $(grep -v "$2"|"$3" $message)
does the following:
It sets a variable words to the empty string for the environment of the command (because there is a blank after =).
It tries to set up a pipeline consisting of two commands, grep -v "$2" and "$3" $message. The first of these commands would just hang and wait for input; the second one tries to run the contents of $3 as a command; presumably, based on your error message, $3 contains First.
If the pipeline would actually run, its output would be run as a command (again because of the blank to the right of =).
Who can simply explain
what is the difference between $* and $#?
Why there are two variables for same content as above?
There is no difference if you do not put $* or $# in quotes. But if you put them inside quotes (which you should, as a general good practice), then $# will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.
Take these scripts (foo.sh and bar.sh) for testing:
>> cat bar.sh
echo "Arg 1: $1"
echo "Arg 2: $2"
echo "Arg 3: $3"
echo
>> cat foo.sh
echo '$* without quotes:'
./bar.sh $*
echo '$# without quotes:'
./bar.sh $#
echo '$* with quotes:'
./bar.sh "$*"
echo '$# with quotes:'
./bar.sh "$#"
Now this example should make everything clear:
>> ./foo.sh arg1 "arg21 arg22" arg3
$* without quotes:
Arg 1: arg1
Arg 2: arg21
Arg 3: arg22
$# without quotes:
Arg 1: arg1
Arg 2: arg21
Arg 3: arg22
$* with quotes:
Arg 1: arg1 arg21 arg22 arg3
Arg 2:
Arg 3:
$# with quotes:
Arg 1: arg1
Arg 2: arg21 arg22
Arg 3: arg3
Clearly, "$#" gives the behaviour that we generally want.
More detailed description:
Case 1: No quotes around $* and $#:
Both have same behaviour.
./bar.sh $* => bar.sh gets arg1, arg2 and arg3 as separate arguments
./bar.sh $# => bar.sh gets arg1, arg2 and arg3 as separate arguments
Case 2: You use quotes around $* and $#:
./bar.sh "$*" => bar.sh gets arg1 arg2 arg3 as a single argument
./bar.sh "$#" => bar.sh gets arg1, arg2 and arg3 as a separate arguments
More importantly, $* also ignores quotes in your argument list. For example, if you had supplied ./foo.sh arg1 "arg2 arg3", even then:
./bar.sh "$*" => bar.sh will still receive arg2 and arg3 as separate parameters!
./bar.sh "$#" => will pass arg2 arg3 as a single parameter (which is what you usually want).
Notice again that this difference occurs only if you put $* and $# in quotes. Otherwise they have the same behaviour.
Official documentation: http://www.gnu.org/software/bash/manual/bash.html#Special-Parameters
Aside from the difference as described in the technical documents, it is best shown using some examples:
Lets assume we have four shell scripts, test1.sh:
#!/bin/bash
rm $*
test2.sh:
#!/bin/bash
rm "$*"
test3.sh:
#!/bin/bash
rm $#
test4.sh:
#!/bin/bash
rm "$#"
(I am using rm here instead of echo, because with echo, one can not see the difference)
We call all of them with the following commandline, in a directory which is otherwise empty:
./testX.sh "Hello World" Foo Bar
For test1.sh and test3.sh, we receive the following output:
rm: cannot remove ‘Hello’: No such file or directory
rm: cannot remove ‘World’: No such file or directory
rm: cannot remove ‘Foo’: No such file or directory
rm: cannot remove ‘Bar’: No such file or directory
This means, the arguments are taken as a whole string, joined with spaces, and then reparsed as arguments and passed to the command. This is generally not helpful when forwarding arguments to another command.
With test2.sh, we get:
rm: cannot remove ‘Hello World Foo Bar’: No such file or directory
So we have the same as for test{1,3}.sh, but this time, the result is passed as one argument.
test4.sh has something new:
rm: cannot remove ‘Hello World’: No such file or directory
rm: cannot remove ‘Foo’: No such file or directory
rm: cannot remove ‘Bar’: No such file or directory
This implies that the arguments are passed in a manner equivalent to how they were passed to the the script. This is helpful when passing arguments to other commands.
The difference is subtle, but will bite you when passing arguments to commands which expect information at certain points in the command line and when spaces take part in the game. This is in fact a good example of one of the many pitfalls of most shells.
see this here :
$# Stores the number of command-line arguments that
were passed to the shell program.
$? Stores the exit value of the last command that was
executed.
$0 Stores the first word of the entered command (the
name of the shell program).
$* Stores all the arguments that were entered on the
command line ($1 $2 ...).
"$#" Stores all the arguments that were entered
on the command line, individually quoted ("$1" "$2" ...).
take an example
./command -yes -no /home/username
so now..
$# = 3
$* = -yes -no /home/username
$# = ("-yes" "-no" "/home/username")
$0 = ./command
$1 = -yes
$2 = -no
$3 = /home/username
They are different when quoted:
$ set "a b" c d
$ echo $#
3
$ set "$*"
$ echo $#
1
$ set "a b" c d
$ echo $#
3
$ set "$#"
$ echo $#
3
Here only the second form preserves the argument count.
I have created a script in sh shell.
#script.sh
echo $1
if [ x$1 = 'x' ]
then
echo CODE1
else
echo CODE2
fi
1) if I am running it using . ./script.sh
OUTPUT: CODE1
2) If I run it like . ./script.sh arg1
OUTPUT: arg1
CODE2
3)if I run it again after using . ./script.sh
then it gives me
OUTPUT: arg1
CODE2
I think 3rd has same output as 2nd because I am running 3rd in the same shell as 2nd so $1 is not deallocated and 3rd is actully using the value of $1 set by 2nd.
But if I deallocate it using unset 1 then shell is giving error as unknown identifire.
How can I deallocate this environment variable $1 ?
OR
How can I set it to null.
By sourcing your shell with ., you're running it in the context of your current shell. If you just don't do that, none of these problems will happen:
$ ./script.sh
CODE1
$ ./script.sh arg1
arg1
CODE2
$ ./script.sh
CODE1
I have a programme, ./a that I run in a loop in shell.
for((i=1 ; i<=30; i++)); do
./a arg1 5+i &//arg2 that I need to pass in which is the addition with the loop variables
done
How could I passed in the arg2 which is the addition with loop variables?
Also, I has another programme which is ./b which I need to run once and takes in all the 5 +i arguments. How could I do that without hardcoded it.
./b arg1 6\
7\
8\
9\.....
Thanks.
Addition is performed with the same (()) you are already using, while concatenation is done simply with "":
for((i=1 ; i<=30; i++)); do
let j=$((5+i))
list="$list $j"
./a arg1 $j
done
./b $list
This should work:
( for((i=5 ; i<=30; i++)); do ./a $((5+i)); echo $((5+i)); done ) | xargs ./b
In current bash versions you can use the {a..b} range notation. E.g.
for i in {1..30}; do
./a arg1 $i
done
./b arg1 {6..35}
For your second part I would do it like this
./b arg1 $(seq 6 35)
Or if you really require the addition within a loop
declare -a list
for n in $(seq 1 30) ; do
list=("${list[#]}" $((5+n)))
done
./b arg1 ${list[#]}
I need to call another shell script testarg.sh within my main script. This script testarg.sh has arguments ARG1 ,ARG2, ARG3. I need to call up the below way:
./testarg.sh -ARG1 <value> -ARG2 <value> -ARG3
ARG1 and ARG3 arguments are mandatory ones. If it's not passed to the main script then I quit. ARG2 is an optional one. If the ARG2 variable is not set with value or it's not defined then I need not pass it from main script. So I need to call up the below way
./testarg.sh -ARG1 <VALUE1> -ARG3
If the value exist for the ARG2 Variable then I need to call the below way:
./testarg.sh -ARG1 <VALUE1> -ARG2 <VALUE2> -ARG3
Do I need to have a if else statement for checking the ARG2 variable is empty or null? Is there any other way to do it?
Amendment
If ARG2 is set, then the call should be:
./testarg.sh -ARG1 -OPT2 $ARG2 -ARG3
If this is in bash, you can write
./testarg.sh -ARG1 $ARG1 ${ARG2:+-ARG2 $ARG2} -$ARG3
The construct ${param:+word} evaluates to word if param is set, or nothing otherwise. So if $ARG2 has a value, you get -ARG2 $ARG2, otherwise nothing.
#!/bin/sh
if [ "$1" = "" ]; then
echo ARG1 is null
else
echo ARG1 = $1
fi
if [ "$2" = "" ]; then
echo ARG2 is null
else
echo ARG2 = $2
fi