developer tip

쉘 명령이 실행될 때 에코하는 방법

optionbox 2020. 9. 29. 07:38
반응형

쉘 명령이 실행될 때 에코하는 방법


쉘 스크립트에서 호출 된 모든 쉘 명령을 에코하고 변수 이름을 확장하는 방법은 무엇입니까?

예를 들어 다음 줄이 있습니다.

ls $DIRNAME

스크립트에서 명령을 실행하고 다음을 표시하고 싶습니다.

ls /full/path/to/some/dir

목적은 호출 된 모든 쉘 명령과 해당 인수의 로그를 저장하는 것입니다. 그러한 로그를 생성하는 더 좋은 방법이 있습니까?


set -x또는 set -o xtrace변수를 확장하고 줄 앞에 약간의 + 기호를 인쇄합니다.

set -v또는 set -o verbose인쇄하기 전에 변수를 확장하지 않습니다.

set +xset +v사용 하여 위의 설정을 해제하십시오.

스크립트의 첫 번째 줄에는 나중에 스크립트에서 (또는 ) 과 동일한 효과를 갖도록 #!/bin/sh -x(또는 -v)을 넣을 수 있습니다 .set -x-v

위의 내용은 /bin/sh.

set속성디버깅 에 대한 bash-hackers의 위키를 참조하십시오 .

$ cat shl
#!/bin/bash                                                                     

DIR=/tmp/so
ls $DIR

$ bash -x shl 
+ DIR=/tmp/so
+ ls /tmp/so
$

set -x 당신이 원하는 것을 줄 것입니다.

다음은 시연 할 예제 셸 스크립트입니다.

#!/bin/bash
set -x #echo on

ls $PWD

이렇게하면 모든 변수가 확장되고 명령 출력 전에 전체 명령이 인쇄됩니다.

산출:

+ ls /home/user/
file1.txt file2.txt

당신은 또한에 그들을 배치하여 스크립트의 선택 라인이 토글 set -xset +x

#!/bin/bash
...
if [[ ! -e $OUT_FILE ]];
then
   echo "grabbing $URL"
   set -x
   curl --fail --noproxy $SERV -s -S $URL -o $OUT_FILE
   set +x
fi

에코 기능을 사용하여 명령을 실행합니다.

#!/bin/bash
#function to display commands
exe() { echo "\$ $@" ; "$@" ; }

exe echo hello world

어떤 출력

$ echo hello world
hello world

편집하다:

더 복잡한 명령 파이프 등의 경우 eval을 사용할 수 있습니다.

#!/bin/bash
#function to display commands
exe() { echo "\$ ${@/eval/}" ; "$@" ; }

exe eval "echo 'Hello World' | cut -d ' ' -f1"

어떤 출력

$  echo 'Hello World' | cut -d ' ' -f1
Hello

선택 라인을 울리는에 대한 shuckc의 대답은 몇 가지 단점을 가지고 : 다음으로 끝날 set +x명령뿐만 아니라 에코되고, 당신은 함께 종료 코드를 테스트 할 수있는 기능 잃게 $?가 덮어 도착 이후를 set +x.

또 다른 옵션은 서브 쉘에서 명령을 실행하는 것입니다.

echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )

if [ $? -eq 0 ] ; then
    echo "curl failed"
    exit 1
fi

which will give you output like:

getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed

This does incur the overhead of creating a new subshell for the command, though.


Another option is to put "-x" at the top of your script instead of on the command line:

$ cat ./server
#!/bin/bash -x
ssh user@server

$ ./server
+ ssh user@server
user@server's password: ^C
$

(Insufficient rep to comment on chosen answer.)


According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts

2.3.1. Debugging on the entire script

$ bash -x script1.sh

...

There is now a full-fledged debugger for Bash, available at SourceForge. These debugging features are available in most modern versions of Bash, starting from 3.x.

2.3.2. Debugging on part(s) of the script

set -x            # activate debugging from here
w
set +x            # stop debugging from here

...

Table 2-1. Overview of set debugging options

Short  | Long notation | Result  
-------+---------------+--------------------------------------------------------------
set -f | set -o noglob | Disable file name generation using metacharacters (globbing).  
set -v | set -o verbose| Prints shell input lines as they are read.  
set -x | set -o xtrace | Print command traces before executing command.  

...

Alternatively, these modes can be specified in the script itself, by adding the desired options to the first line shell declaration. Options can be combined, as is usually the case with UNIX commands:

#!/bin/bash -xv

Type "bash -x" on the command line before the name of the bash script. For instance, to execute foo.sh, type:

bash -x foo.sh

You can execute a bash script in debug mode with the -x option.
This will echo all the commands.

bash -x example_script.sh

# Console output
+ cd /home/user
+ mv text.txt mytext.txt


You can also save the -x option in the script. Just specify the -x option in the shebang.

######## example_script.sh ###################
#!/bin/bash -x

cd /home/user
mv text.txt mytext.txt

##############################################

./example_script.sh

# Console output
+ cd /home/user
+ mv text.txt mytext.txt




For zsh echo

 setopt VERBOSE

and for debugging

 setopt XTRACE

For csh and tcsh, you can set verbose or set echo (or you can even set both, but it may result in some duplication most of the time).

The verbose option prints pretty much the exact shell expression that you type.

The echo option is more indicative of what will be executed through spawning.


http://www.tcsh.org/tcsh.html/Special_shell_variables.html#verbose

http://www.tcsh.org/tcsh.html/Special_shell_variables.html#echo


Special shell variables

verbose If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option.

echo If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the -x command line option.


To allow for compound commands to be echoed, I use eval plus Soth's exe function to echo then run the command. This is useful for piped commands that would otherwise only show none or just the initial part of the piped command.

Without eval:

exe() { echo "\$ $@" ; "$@" ; }
exe ls -F | grep *.txt

Outputs:

$
file.txt

With eval:

exe() { echo "\$ $@" ; "$@" ; }
exe eval 'ls -F | grep *.txt'

Which outputs

$ exe eval 'ls -F | grep *.txt'
file.txt

$ cat exampleScript.sh
#!/bin/bash
name="karthik";
echo $name;

bash -x exampleScript.sh

Output is as follows:

enter image description here

참고URL : https://stackoverflow.com/questions/2853803/how-to-echo-shell-commands-as-they-are-executed

반응형