Bash parameter variables in script problem

I have a script that I wrote to switch to root or ran the command as root without a password. I edited the file / etc / sudoers so that my user [matt] has permission to run / bin / su without a password. This is my script "content:

matt: ~ $ cat ~/bin/s
#!/bin/bash

[ "$1" != "" ] && c='-c'

sudo su $c "$*"

If there are no parameters [simple s], it basically calls sudo suwhich goes to root without a password. But if I set the parameters, the variable $ c is equal to "-c", which makes su the execution of one command.

It works well, except when I need to use spaces. For instance:

matt: ~ $ touch file\ with\ spaces
matt: ~ $ s chown matt file\ with\ spaces 
chown: cannot access 'file': No such file or directory
chown: cannot access 'with': No such file or directory
chown: cannot access 'spaces': No such file or directory
matt: ~ $ s chown matt 'file with spaces'
chown: cannot access 'file': No such file or directory
chown: cannot access 'with': No such file or directory
chown: cannot access 'spaces': No such file or directory
matt: ~ $ s chown matt 'file\ with\ spaces'
matt: ~ $ 

How can i fix this?

Also, what's the difference between $ * and $ @ ?

+5
2

, . @John : "$@", ( ) . , , , su -c , , , ( ..), , , , su -c. bash printf :

#!/bin/bash

if [ $# -gt 0 ]; then
    sudo su -c "$(printf "%q " "$@")"
else
    sudo su
fi

, :

  • , s chown matt file\ with\ spaces
  • bash : "s" "chown" "matt" " ". , , , ( : bash , ).
  • bash printf "%q " "$@" script, "$@" script, . printf "%q " "chown" "matt" "file with spaces".
  • printf "% q" " ". : "chown matt file\with\spaces", ( , ).
  • sudo ( $() , sudo). sudo su -c "chown matt file\ with\ spaces ".
  • sudo su , , .
  • su , .
  • , -c: chown matt file\ with\ spaces. , .
  • chown "" " ". , .

bash ?

+8

"$*" ($1, $2,...) , ( , $IFS). , , : "foo bar" foo\ bar . , , "$*" "$1 $2 $3". , "$*" "" ( ).

"$@" - , , . , , "$@" "$1" "$2" "$3". , "$@" ( , ).

"$@" - , , "$*" $* $@ ( (aka globbing) ).

, , su -c, . , , , . https://unix.stackexchange.com/questions/3063/how-do-i-run-a-command-as-the-system-administrator-root sudo su.

sudo root, su. script , ; sudo , : sudo -s. , script :

#!/bin/sh
if [ $# -eq 0 ]; then set -- -s; else set -- -- "$@"; fi
exec sudo "$@"

( else , -.)

script. , . root , , .

+3

All Articles