Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't seem to use the Bash "-c" option with arguments after the "-c" option string

Tags:

bash

eval

The man page for Bash says, regarding the -c option:

-c string 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.

So given that description, I would think something like this ought to work:

bash -c "echo arg 0: $0, arg 1: $1" arg1 

but the output just shows the following, so it looks like the arguments after the -c string are not being assigned to the positional parameters.

arg 0: -bash, arg 1: 

I am running a fairly ancient Bash (on Fedora 4):

[root@dd42 trunk]# bash --version GNU bash, version 3.00.16(1)-release (i386-redhat-linux-gnu) Copyright (C) 2004 Free Software Foundation, Inc.

I am really trying to execute a bit of a shell script with arguments. I thought -c looked very promising, hence the issue above. I wondered about using eval, but I don't think I can pass arguments to the stuff that follows eval. I'm open to other suggestions as well.

like image 890
Chris Markle Avatar asked Nov 10 '09 23:11

Chris Markle


People also ask

What does c option in bash do?

The manual page for Bash (e.g. man bash ) says that the -c option executes the commands from a string; i.e. everything inside the quotes.

What does the c option do in Linux?

c file, and create a debugging version of the executable output file. This output file can be used by the debugger, and is usually much larger in size than the normal output files. cc command with -c option: This command will compile the source_file.

How do you pass arguments in bash?

Arguments passed to a Bash script follow the name of the script in the command line and they are separated from each other by a space. Each argument can be referenced in the script by positional parameters defined by default in Bash ($1, $2, $3, etc…).


2 Answers

You need to use single quotes to prevent interpolation happening in your calling shell.

$ bash -c 'echo arg 0: $0, arg 1: $1' arg1 arg2 arg 0: arg1, arg 1: arg2 

Or escape the variables in your double-quoted string. Which to use might depend on exactly what you want to put in your snippet of code.

like image 83
martin clayton Avatar answered Oct 01 '22 21:10

martin clayton


Because '$0' and '$1' in your string is replaced with a variable #0 and #1 respectively.

Try :

bash -c "echo arg 0: \$0, arg 1: \$1" arg0 arg1

In this code $ of both are escape so base see it as a string $ and not get replaced.

The result of this command is:

arg 0: arg0, arg 1: arg1

Hope this helps.

like image 31
NawaMan Avatar answered Oct 01 '22 22:10

NawaMan