Как вы используете PIPESTATUS, тройник и / bin / sh вместе?

4243
Yasser Zamani

Когда я бегу

curl | tee test.txt; echo $ 

Я правильно вижу

curl: попробуйте 'curl --help' или 'curl --manual' для получения дополнительной информации

2

Но когда я пытаюсь запустить точно такую ​​же команду, используя '/ bin / sh':

sh -c "curl | tee test.txt; echo \$" 

я получил

curl: попробуйте 'curl --help' или 'curl --manual' для получения дополнительной информации

sh: 1: плохая замена

Как мы можем решить Bad substitutionпроблему, пожалуйста?

4
Возможный дубликат [Как получить PIPESTATUS и вывод в сценарии bash] (https://superuser.com/questions/425774/how-to-get-both-pipestatus-and-output-in-bash-script) jww 6 лет назад 1
@jww, они работают через `sh -c"«`? Yasser Zamani 6 лет назад 0

3 ответа на вопрос

5
grawity

You solve it by not using sh.

The PIPESTATUS variable specifically, and the $ array syntax in general, are features specific to the Bash shell. They do not exist in POSIX sh, and even shells that do have arrays might use a different syntax.

It just happens that some Linux distributions symlink their /bin/sh to Bash. Other distributions, however, symlink it to dash, Debian Almquist Shell. Both are compatible with POSIX sh scripts, but only Bash accepts the $ syntax.

So if you want to use it, run bash -c "…" instead.

Потому что его часть вопроса использовать `sh`. Лучше ответьте ниже, со взломом. Не лучшее «решение», хотя (я согласен, что лучшее решение - избегать `sh`) Dr Beco 8 лет назад 0
3
rzr

Workaound for '/bin/sh' or busybox

status=0 eval ` { ls /dontexists || echo status="$?"; } | tee /dev/null` echo "# status=$" 

Trace :

busybox sh ~/bin/test.sh + status=0 + ls /dontexists + tee /dev/null ls: /dontexists: No such file or directory + echo status=1 + eval status=1 + status=1 + echo # status=1 # status=1 
1
atmchem

Также 'bash -c', похоже, имеет проблему с ним при вызове из tcsh:

bash -c "curl | tee test.txt; echo \$"

PIPESTATUS: неопределенная переменная.

Это работает для меня из tcsh:

bash -c 'curl | tee test.txt; echo $'

curl: попробуйте 'curl --help' или 'curl --manual' для получения дополнительной информации
2

GNU bash, версия 4.2.25 (1) -релиз (x86_64-pc-linux-gnu),
вызванный из tcsh 6.17.06

Похожие вопросы