Uvais Ibrahim
Uvais Ibrahim

Reputation: 169

shell scripting echo not working inside sudo

I have a shell script test.sh as give below.

sudo -H sh -c '
    echo $1;    
'

But while I am running this script as ./test.sh abcd it is not echoing anything. Then I changed my script as given below.

sudo -H sh -c '
    echo \$1;    
'

But now, it is displaying output as $1. What modification shall I need to do here for getting output as abcd. Please advice as I am a very beginner in shell scripting.

Thanks.

Upvotes: 1

Views: 1273

Answers (2)

chan
chan

Reputation: 26

Try:

sudo -H sh -c '
echo "$1";    
' argv0 "$1"

From the bash man page:

man bash | less -Ip '-c string'

# -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.

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Try this:

sudo -H sh -c "
  echo $1;    
"

sudo runs the command in a new shell that doesn't know anything about the argument(s) passed to its parent, so you need to expand them before running the command string in the new (sub)shell.

Upvotes: 2

Related Questions