Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to /bin/bash via a bash script

Tags:

bash

I am writing a bash script that takes a number of command line arguments (possibly including spaces) and passes all of them to a program (/bin/some_program) via a login shell. The login shell that is called from the bash script will depend on the user's login shell. Let's suppose the user uses /bin/bash as their login shell in this example... but it might be /bin/tcsh or anything else.

If I know how many arguments will be passed to some_program, I can put the following lines in my bash script:

#!/bin/bash
# ... (some lines where we determine that the user's login shell is bash) ...
/bin/bash --login -c "/bin/some_program \"$1\" \"$2\""

and then call the above script as follows:

my_script "this is too" cool

With the above example I can confirm that some_program receives two arguments, "this is too" and "cool".

My question is... what if I don't know how many arguments will be passed? I'd like to pass all the arguments that were sent to my_script along to some_program. The problem is I can't figure out how to do this. Here are some things that don't work:

/bin/bash --login -c "/bin/some_program $@"     # --> 3 arguments: "this","is","too"
/bin/bash --login -c /bin/some_program "$@"     # --> passes no arguments
like image 910
JCOidl Avatar asked Aug 21 '12 16:08

JCOidl


2 Answers

Quoting the bash manual for -c:

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

Works for me:

$ cat x.sh
#!/bin/bash
/bin/bash --login -c 'echo 1:$1 2:$2 3:$3' echo "$@"
$ ./x.sh "foo bar" "baz" "argh blargh quargh"
1:foo bar 2:baz 3:argh blargh quargh

I don't know how you arrived at the "passes no arguments" conclusion, maybe you missed the $0 bit?

like image 172
themel Avatar answered Dec 02 '22 13:12

themel


Avoid embedding variables into other scripts, pass them on as arguments instead. In this case:

bash --login -c 'some_program "$@"' some_program "$@"

The first argument after -c '...' is taken as $0, so I just put in some_program there.

On a side note, it's an odd requirement to require a login shell. Doesn't the user log in?

like image 21
geirha Avatar answered Dec 02 '22 15:12

geirha