2015-01-19 3 views
0

Я вошел в систему как root Однако, я пытаюсь запустить java-программу из сценария bash с использованием другого пользователя с именем marshell. Я получаю следующую ошибку, не уверен, что я делаю неправильно?Как запустить команду bash в качестве обычного пользователя?

#!/bin/bash 
sudo su marshell <<'EOF' 
CP=/home/marshell/sanity_test_scripts/ # The classpath to use 
java -cp $CP JavaRunCommand $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} 
EOF 

Обновлено:

#!/bin/bash 
su marshell <<EOF 
CP=/home/marshell/sanity_test_scripts/US_SOUTH/YP/DataWorks/free 
java -cp "$CP" JavaRunCommand "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" "${10}" 
EOF 

Ошибка:

[email protected]:bash runbash_marshell.sh https://api.xyz.net [email protected] pass AllServices test Data free data-monitor Y00 UKLONDON 

runbash_marshell.sh: line 5: warning: here-document at line 3 delimited by end-of-file (wanted `EOF') 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
     at JavaRunCommand.main(JavaRunCommand.java:308) 
bash: line 2: EOF: command not found 
+2

Хотя я не могу найти acutal ошибку, musn't процитировать 'EOF', если вам нужны ваши позиционные параметры расширены. Во всяком случае, это лучший подход: 'java -cp $ CP JavaRunCommand" $ @ "' и не забудьте выставить комментарий «EOF» в вашем случае: 'sudo su marshell << EOF' – whoan

+0

Почему вы используете' sudo' если вы уже вошли в систему под учетной записью root? –

+0

runbash_marshell.sh: строка 5: предупреждение: здесь-документ в строке 2, ограниченный конечным файлом (требуется «EOF») ................ bash: строка 3: EOF: команда не найдена @ja Я обновил свой код, как было предложено, и он работает, но я все еще вижу предупреждение выше, не уверенное почему? – user3846091

ответ

0

Почему бы не использовать флаг команды -c для су как

> foo=bar; su marshell -c "./suc $foo" bar

ш здесь скрипт просто печатает весь переданный ему параметр. В вашем конкретном случае она должна выглядеть как

> su marshell -c "CP=/home/marshell/sanity_test_scripts/; java -cp $CP JavaRunCommand $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}"

или

> sudo -u marshell -i "CP=/home/marshell/sanity_test_scripts/; java -cp $CP JavaRunCommand $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}"

Для Судо вы могли бы использовать что-то вроде параметров -u и -i.

-u user  The -u (user) option causes sudo to run the specified 
       command as a user other than root. To specify a uid 
       instead of a user name, use #uid. When running commands as 
       a uid, many shells require that the '#' be escaped with a 
       backslash ('\'). Security policies may restrict uids to 
       those listed in the password database. The sudoers policy 
       allows uids that are not in the password database as long 
       as the targetpw option is not set. Other security policies 
       may not support this. 

-i [command] The -i (simulate initial login) option runs the shell 
       specified by the password database entry of the target user 
       as a login shell. This means that login-specific resource 
       files such as .profile or .login will be read by the shell. 
       If a command is specified, it is passed to the shell for 
       execution via the shell's -c option. If no command is 
       specified, an interactive shell is executed. sudo attempts 
       to change to that user's home directory before running the 
       shell. The security policy shall initialize the 
       environment to a minimal set of variables, similar to what 
       is present when a user logs in. The Command Environment 
       section in the sudoers(5) manual documents how the -i 
       option affects the environment in which a command is run 
       when the sudoers policy is in use. 
0

Необходимо процитировать детали, которые должны передаваться дословно. Если ваши аргументы командной строки foo, bar, baz и quux, и вы хотите Java, чтобы выполнить

java -cp "$CP" JavaRunCommand foo bar baz quux 

, то вам необходимо интерполировать аргументы командной строки, но цитата (знак доллара в) $CP так он не интерполируется текущей оболочкой.

#!/bin/bash 
sudo su marshell <<EOF 
CP=/home/marshell/sanity_test_scripts/ # The classpath to use 
java -cp "\$CP" JavaRunCommand [email protected] 
EOF 

Это, к сожалению, не правильно процитировать какие-либо аргументы, содержащие пробелы.

Гораздо лучше было быть на самом деле

sudo -u marshell java -cp /home/marshell/sanity_test_scripts/ JavaRunCommand "[email protected]" 
Смежные вопросы