때로는 명령을 실행할 때 출력이 표시되지 않으므로 제대로 작동했는지 확실하지 않습니다. 모든 명령이 올바르게 실행되었는지 피드백을 받도록 할 수 있습니까? 또는 최소한 그들이 실행 한 피드백 ID를 표시하려면 (정확하게 또는 아닙니다)
답변
(당신이 Ask Ubuntu에 게시 한 이후 기본 쉘 인 Bash에 대해 이야기한다고 가정 할 수 있습니다 .)
스택 오버플로 질문 에는 아주 좋은 대답 이 있습니다. 쉘 스크립트에서 : 쉘 명령이 실행될 때 에코 명령을 보내십시오 (이것은 우분투 전용 솔루션이 아닙니다).
set 명령을 사용하여 verbose 또는 xtrace를 켜십시오.
set -o
당신에게 현재의 매개 변수로 전환되는 목록이 제공됩니다 에 또는 오프 .
set -v
또는 longform 버전 :
set -o verbose
verbose가 켜 집니다 .
그래도 원하는 것은 실제로 xtrace라고 생각합니다. 이렇게하면 실행하는 모든 명령이 에코 될뿐만 아니라 매개 변수가 확장되고 더 많은 피드백이 제공됩니다. 따라서 터미널에서 ‘hi’를 입력하는 것처럼 바보 같은 일을하면 입력 한 내용의 에코뿐만 아니라 쉘이 ‘hi’명령을 실행하려고 시도한 것에 대한 보고서 / 추적을 얻습니다 (아래 스크린 샷 참조) ) :
xtrace를 활성화하려면
set -x
또는:
set -o xtrace
이러한 매개 변수를 비활성화하려면 대시 또는 빼기 기호 대신 더하기 기호 + 를 제외하고 동일한 명령을 반 직관적으로 호출합니다 . 예를 들면 다음과 같습니다.
set +v
비슷하게 verbose를 끕니다 .
set +x
xtrace가 꺼 집니다.
쉘 옵션에 대한 자세한 안내서는 제 33 장 옵션, 고급 Bash 스크립팅 안내서를 참조하십시오 .
답변
일부 명령이 성공적으로 작동했는지 확인하려면 다음 을 사용하여 이전 명령 의 반환 상태를 확인할 수 있습니다 $?
.
echo $?
반환 상태 0
는 명령이 성공적으로 완료되었음을 의미하지만 0이 아닌 출력 ( error code )은 일부 문제가 발생했거나 오류가 있고 범주를 오류 코드에서 알 수 있음을 의미합니다. Linux / C 오류 코드는 /usr/include/asm-generic/errno-base.h
및에 정의되어 /usr/include/asm-generic/errno.h
있습니다.
또한 bash에서 완료 상태를 알리는 데 사용할 수 .bashrc
있는 별명 alert
을 정의합니다 . 다음과 같이 명령 또는 명령 콤보로 별명을 첨부해야합니다.
some_command --some-switch; alert
파일에 다음 코드 줄을 추가 하여 마지막으로 실행 된 명령 ~/.bashrc
의 반환 상태 를 표시 할 수 있습니다 .
# show the return code of last command executed PS1='${debian_chroot:+($debian_chroot)}\u@\h(lst ret. $(echo $?) ):\w\$ '
( ~/.bashrc
선택한 텍스트 편집기로 파일 을 열고 위의 행을 복사하여 파일에 붙여 넣은 후 저장하십시오. 터미널의 새 인스턴스를 시작하면 실제로 작동해야합니다. 대신 일부 기능을 정의하여 사용할 수 있습니다. 그와 PS1
같은 추천 아래 그림).
약간의 데모 :
hash@precise(lst ret. 0 ):~$ ls -sh someFileThatsNotThere
ls: cannot access someFileThatsNotThere: No such file or directory
hash@precise(lst ret. 2 ):~$
hash@precise(lst ret. 2 ):~$ aCommandThatsNot
aCommandThatsNot: command not found
hash@precise(lst ret. 127 ):~$
hash@precise(lst ret. 127 ):~$ echo "you should get a lst ret. 0, I believe the system has echo installed :)"
you should get a lst ret. 0, I believe the system has echo installed :)
hash@precise(lst ret. 0 ):~$
hash@precise(lst ret. 0 ):~$ sudo touch /tmp/someTestFile
[sudo] password for hash:
hash@precise(lst ret. 1 ):~$
hash@precise(lst ret. 1 ):~$ chown $USER:$USER /tmp/someTestFile
chown: changing ownership of `/tmp/someTestFile': Operation not permitted
그냥 PS1
🙂 .. 조금 더 놀고
function showRetStat { ## line1: initiliazing retStat with the return status of the previous command retStat=$? ## line2: Left padding the return status with spaces. If you prefer the unpadded one, you can just replace # $retStatFtd in the lines initializing noErrStr and errStr among other possible ways. retStatFtd=$(sed -e :a -e 's/^.\{1,2\}$/ &/;ta' <<< $retStat) ## lines3&4: Setting the strings to display for a successful and unsuccessful run of previous command # which we are going to display with the prompt string. Change the strings to display text of your # choice like you may set noErrStr="yippie!" , errStr="oopsie!" in place of what they're now. noErrStr="retStat "$retStatFtd" :: PASS ^_^" errStr="retStat "$retStatFtd" :: FAIL x_x" ## line5: Applying the logic and display the proper string at the prompt. Space padded number i.e. retStatFtd, here, # worked in the logic, originally I intended to use this for the display while retStat in the conditional # check; you could make the function one statement less if you want to. echo "$([ $retStatFtd = 0 ] && echo "$noErrStr" || echo "$errStr")" } ## Combining the function showRetStat into the prompt string. PS1='${debian_chroot:+($debian_chroot)}\u@\h($(showRetStat)):\w\$ '
(@gronostaj가 자신의 게시물에서하는 것과 같이 더 멋지게 기능을 수정할 수 있습니다.)
답변
이전 명령이 0으로 종료되면 녹색 체크 표시가 나타나고 그렇지 않으면 빨간색 X가 표시되도록 명령 프롬프트를 변경할 수 있습니다. Arch Linux Wiki 에는 다음과 같은 코드를 추가 할 수 있습니다 bash.rc
.
set_prompt () {
Last_Command=$? # Must come first!
Blue='\[\e[01;34m\]'
White='\[\e[01;37m\]'
Red='\[\e[01;31m\]'
Green='\[\e[01;32m\]'
Reset='\[\e[00m\]'
FancyX='\342\234\227'
Checkmark='\342\234\223'
# Add a bright white exit status for the last command
#PS1="$White\$? "
# If it was successful, print a green check mark. Otherwise, print
# a red X.
if [[ $Last_Command == 0 ]]; then
PS1+="$Green$Checkmark "
else
PS1+="$Red$FancyX "
fi
# If root, just print the host in red. Otherwise, print the current user
# and host in green.
if [[ $EUID == 0 ]]; then
PS1+="$Red\\h "
else
PS1+="$Green\\u@\\h "
fi
# Print the working directory and prompt marker in blue, and reset
# the text color to the default.
PS1+="$Blue\\w \\\$$Reset "
}
PROMPT_COMMAND='set_prompt'
(실제 오류 코드는 마음에 들지 않기 때문에 비활성화했습니다. 정확한 코드를 보려면 #
이 줄에서 제거하십시오 . #PS1="$White\$? "
)
그 모습은 다음과 같습니다.
답변
예 , 터미널에서 실행 한 모든 명령에 대한 피드백을 얻을 수 있습니다. 명령을 echo $?
성공적으로 완료하면 0을 반환하고 실패하면 0 이외의 다른 값을 기준으로 작동합니다.
성공 또는 실패 피드백을 얻으려면 아래 줄을 ~/.bashrc
파일에 추가 하십시오.
bind 'RETURN: ";if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;\n"'
그런 다음 소스 ~/.bashrc
파일을 사용하십시오.
source ~/.bashrc
설명:
터미널에서 실행 한 모든 명령에 대해이 ;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
코드는 자동으로 바인딩됩니다.
예:
$ sudo apt-cache policy firefox;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
firefox:
Installed: 24.0+build1-0ubuntu1
Candidate: 24.0+build1-0ubuntu1
Version table:
*** 24.0+build1-0ubuntu1 0
500 http://ubuntu.inode.at/ubuntu/ saucy/main amd64 Packages
100 /var/lib/dpkg/status
SUCCESS
$ suda apt-get update;if [[ $? == 0 ]]; then tput setaf 6 && echo SUCCESS; tput sgr0; else tput setaf 1 && echo FAILURE; tput sgr0; fi;
No command 'suda' found, did you mean:
Command 'sudo' from package 'sudo-ldap' (universe)
Command 'sudo' from package 'sudo' (main)
suda: command not found
FAILURE