1

Let's say I've got this script :

x-terminal-emulator -e bash -c 'echo hello > ~/text'

I call it foo.sh and make it executable.

If I execute this script I'll have a text file in my home folder containing the word 'hello'.

Now if I modify it to this :

x-terminal-emulator -e bash -c 'echo $1 > ~/text'

... and I execute it in a terminal like this :

./foo.sh hello

I get a text file in my home folder containing nothing.

foo.sh receives 'hello' as the first and only argument ($1). So why doesn't bash receive it ? Is there a way to pass one or several arguments from foo.sh to bash ?

I tried to store the argument inside a variable name and then export it but it didn't change the result.

2

From man bash


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

So you can do

x-terminal-emulator -e bash -c 'echo $0 > ~/text' "$1"

or (if you prefer to preserve the "usual" numbering of parameters)

x-terminal-emulator -e bash -c 'echo $1 > ~/text' _ "$1"

where _ can be replaced with any dummy variable of your choice.

1

In bash -c 'echo $1 > ~/text', $1 was expanded in bash -c process, not in your script. You need to pass the original $1 to bash -c:

x-terminal-emulator -e "bash -c 'echo \$1 > ~/text' bash $1"
  • Why complicate things? Why not just use double quotes: x-terminal-emulator -e bash -c "echo $1 > ~/text". Also, I can't get yours to work, it gives an error, but I don't understand why escaping the dollar would help. That just tells bash -c to echo its $1 as far as I can tell. – terdon Jul 30 '15 at 16:00
  • @terdon: I got error unknown option -c with xfce4-terminal -e bash -c 'echo \$@;sleep 10' _ 123, so wrapping command in the whole string can be more portable. And some time you only need using several of parameters, so "bash -c 'echo \$@ > ~/text' bash $1 $2 $3" is easier. – cuonglm Jul 30 '15 at 16:05
  • I get an error with this one :). In any case, why would escaping the dollar help? – terdon Jul 30 '15 at 16:08
  • @terdon: it prevents $1 from being expanded by parent shell. Example in "bash -c 'echo $1 $2 $3 > ~/text' bash $2 $1 $3", then $1 inside bash -c isn't $1 that you passed to it. – cuonglm Jul 30 '15 at 16:12
  • No, of course not, but the OP wants the $1 from the shell script, they're not actually passing anything to the bash -c process. They want to get $1 as given on the command line. I just don't see the point of passing $1 again since it's already defined. – terdon Jul 30 '15 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.