2016-08-25 5 views
2

sudo bash -c을 사용하여 쉘 명령을 실행할 때 변수 확장을 제어하고 싶습니다.Bash - 어떻게 서브 쉘 문자열에서 리터럴을 강제 하시겠습니까?

는 내가 보통 쉘에서 그것을 할 수 있습니다 알고

bash$ export FOO=foo 
bash$ export BAR=bar 
bash$ echo "expand $FOO but not "'$BAR'"" 
expand foo but not $BAR 

어떻게이 sudo bash -c을 사용하여 상기 할 수 있습니까?

bash$ sudo bash -c "echo "expand $FOO but not "'$BAR'""" 
expand 
bash$ sudo bash -c 'echo "expand $FOO but not "'$BAR'""' 
expand but not bar 

답변

3
당신은 당신이 확장하지 않는 탈출 $ 이것을 사용할 수 있습니다

:

# original echo replaced with printf 
$> printf 'expand %s but not %s\n' "$FOO" '$BAR' 
expand foo but not $BAR 

# prints in here-doc with bash 
$> bash<<-'EOF' 
printf 'expand %s but not %s\n' "$FOO" '$BAR' 
EOF 
expand foo but not $BAR 
+1

. http://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo – shj

0

패스 인수를 : 나는 탈출 방지하기 위해 여기-문서를 사용하는 것이 좋습니다 그러나

$> bash -c "echo \"expand $FOO but not \"'\$BAR'" 
expand foo but not $BAR 

bash으로 전달할 문자열을 생성하는 대신

$ bash -c 'echo "expand $1 but not $2"' _ "$FOO" '$BAR' 
expand 5 but not $BAR 

합니다 (_-c에 의해 지정된 스크립트에서 $0을 설정하는 단지 더미 값입니다.) 루트 ENV에서 일할 여기-문서를 사용 sudo는 -E를 들어