Bash의 숨겨진 기능
쉘 스크립트는 자동화 및 간단한 일회성 작업을위한 접착제로 자주 사용됩니다. Bash 쉘 / 스크립팅 언어에서 가장 좋아하는 "숨겨진"기능은 무엇입니까?
- 답변 당 하나의 기능
- 문서에 대한 링크뿐만 아니라 기능에 대한 예와 간단한 설명을 제공합니다.
- 첫 번째 줄로 굵은 제목을 사용하여 지형지 물에 레이블 지정
또한보십시오:
- C의 숨겨진 기능
- C #의 숨겨진 기능
- C ++의 숨겨진 기능
- Delphi의 숨겨진 기능
- Python의 숨겨진 기능
- 자바의 숨겨진 기능
- JavaScript의 숨겨진 기능
- Ruby의 숨겨진 기능
- PHP의 숨겨진 기능
- Perl의 숨겨진 기능
- VB.Net의 숨겨진 기능
이전 줄의 마지막 매개 변수 삽입
alt- .지금까지 가장 유용한 키 조합입니다. 시도해보고 확인해보세요. 어떤 이유에서인지 아무도이 키에 대해 알지 못합니다.
이전 마지막 매개 변수를 선택하려면이 버튼을 반복해서 누릅니다.
방금 전에 사용한 것에 대해 다른 작업을하고 싶을 때 좋습니다.
로그 아웃 한 후에도 프로세스를 계속 실행하려면 :
disown -h <pid>
유용한 bash 내장입니다. 과 달리 이미 실행중인 프로세스에서 nohup실행할 수 있습니다 disown.
먼저 control-Z로 작업을 중지하고에서 pid를 가져오고 ps(또는 사용 echo $!)을 사용 bg하여 백그라운드로 보낸 다음 disown-h 플래그와 함께 사용 합니다.
작업을 백그라운드로 작성하는 것을 잊지 마십시오. 그렇지 않으면 로그 아웃 할 때 종료됩니다.
매뉴얼의 EXPANSION 섹션에 나열된 거의 모든 것
특히, 매개 변수 확장 :
$ I=foobar
$ echo ${I/oo/aa} #replacement
faabar
$ echo ${I:1:2} #substring
oo
$ echo ${I%bar} #trailing substitution
foo
$ echo ${I#foo} #leading substitution
bar
내가 좋아하는 것:
sudo !!
sudo로 이전 명령을 다시 실행하십시오.
더 많은 매직 키 조합 :
Ctrl+ r는 명령 내역을 통해 "역 증분 검색"을 시작합니다. 입력을 계속하면 입력 한 모든 텍스트가 포함 된 가장 최근 명령을 검색합니다.
Tab 지금까지 입력 한 단어가 모호하지 않은 경우 완성됩니다.
Tab Tab 지금까지 입력 한 단어의 모든 완성을 나열합니다.
Alt+ 가능한 모든 완성을 * 삽입 합니다. 예를 들어 와일드 카드를 사용하여 잠재적으로 파괴적인 명령을 입력 한 경우 특히 유용합니다.
rm -r source/d*.cAlt + *
rm -r source/delete_me.c source/do_not_delete_me.cCtrl+ Alt+ e는 현재 줄에서 별칭, 내역 및 셸 확장을 수행합니다. 즉, 현재 행이 쉘에서 처리 될 때 다시 표시됩니다.
ls $HOME/tmpCtrl Alt + e
ls -N --color=tty -T 0 /home/cramey
기록 명령 및 인수 가져 오기
!연산자를 사용하여 이전 명령 및 인수에 선택적으로 액세스 할 수 있습니다. 긴 경로로 작업 할 때 매우 유용합니다.
을 사용하여 마지막 명령을 확인할 수 있습니다 history.
당신이 이전 명령을 사용할 수 !<n>있는 n의 명령의 인덱스 history, 음수 역사의 마지막 명령의 뒤쪽으로는 계산합니다.
ls -l foo bar
touch foo bar
!-2
이전 인수를 !:<n>, 0은 명령,> = 1은 인수와 함께 사용할 수 있습니다 .
ls -l foo
touch !:2
cp !:1 bar
그리고 두 가지를 결합 할 수 있습니다. !<n>:<m>
touch foo bar
ls -l !:1 !:2
rm !-2:1 !-2:2
!-2
인수 범위를 사용할 수도 있습니다. !<n>:<x>-<y>
touch boo far
ls -l !:1-2
기타 !특수 수정자는 다음과 같습니다.
*모든 논쟁에 대해ls -l foo bar ls !*^첫 번째 인수 (!:1==!^)$마지막 논쟁을 위해ls -l foo bar cat !$ > /dev/null
나는 -x 기능을 좋아하여 스크립트에서 무슨 일이 일어나고 있는지 볼 수 있습니다.
bash -x script.sh
SECONDS=0; sleep 5 ; echo "that took approximately $SECONDS seconds"
SECONDS
이 매개 변수가 참조 될 때마다 쉘 호출이 리턴 된 이후의 시간 (초)입니다. SECONDS에 값이 할당 된 경우 후속 참조시 반환되는 값은 할당 이후에 할당 된 값을 더한 시간 (초)입니다. SECONDS가 설정되지 않은 경우 이후에 재설정 되더라도 특수 속성이 손실됩니다.
제가 가장 좋아하는 것 중 하나입니다. 이렇게하면 탭 완성이 대소 문자를 구분하지 않도록 설정됩니다. 특히 파일 시스템이 기본적으로 대소 문자를 구분하지 않는 Mac에서 디렉토리 경로를 빠르게 입력하는 데 정말 좋습니다. 나는 이것을 .inputrc나의 홈 폴더에 넣었다 .
set completion-ignore-case on
무작위 특수 변수 :
if [[ $(($RANDOM % 6)) = 0 ]]
then echo "BANG"
else
echo "Try again"
fi
정규식 처리
최근 bash 릴리스에는 정규식 일치 기능이 있으므로 다음을 수행 할 수 있습니다.
if [[ "mystring" =~ REGEX ]] ; then
echo match
fi
여기서 REGEX는 man re_format에서 설명하는 형식의 원시 정규식입니다.
괄호로 묶인 부분의 일치 항목은 요소 1부터 시작하여 BASH_REMATCH 배열에 저장되므로 (요소 0은 전체적으로 일치하는 문자열 임)이를 사용하여 정규식 구문 분석을 수행 할 수도 있습니다.
Ctrlx Ctrle
그러면 현재 명령이 VISUAL 변수에 정의 된 편집기로로드됩니다. 이것은 여기에 나열된 것과 같은 긴 명령에 매우 유용합니다.
vi를 편집기로 사용하려면 :
export VISUAL=vi
오타의 빠르고 더러운 수정 (특히 명령 기록을 사용하고 스크롤하는 것이 끔찍한 느린 연결에서 긴 명령에 유용함) :
$ cat /proc/cupinfo
cat: /proc/cupinfo: No such file or directory
$ ^cup^cpu
또한 !:s/old/new이전 명령에서 old를 new로 대체하는 것을 한 번 시도하십시오 .
많은 발생을 대체하려면 !:gs/old/new.
히스토리 이벤트와 함께 gs및 s명령을 사용할 수 있습니다.
!-2:s/old/new
대체 할 수 old와 new마지막 명령의 두 번째 (한 번).
내가 가장 좋아하는 두 가지 :
실제로 스크립트를 실행하지 않고 구문을 확인하려면 다음을 사용하십시오.
bash -n script.sh
마지막 디렉토리로 돌아가십시오 (예, 푸시 및 팝을 알고 있지만 더 빠릅니다)
cd -
중위 부울 연산자 사용
다음과 같은 경우 간단한 것을 고려하십시오.
if [ 2 -lt 3 ]
then echo "Numbers are still good!"
fi
그건 좀 못 생겼어. 별로 현대적이지 않습니다. 부울 표현식 주위에 이중 대괄호를 사용하면 일반 부울 연산자를 사용할 수 있습니다!
if [[ 2 < 3 ]]
then echo "Numbers are still good!"
fi
어레이 :
#!/bin/bash
array[0]="a string"
array[1]="a string with spaces and \"quotation\" marks in it"
array[2]="a string with spaces, \"quotation marks\" and (parenthesis) in it"
echo "There are ${#array[*]} elements in the array."
for n in "${array[@]}"; do
echo "element = >>${n}<<"
done
배열 (및 기타 고급 bash 스크립팅 항목)에 대한 자세한 내용은 Advanced Bash-Scripting Guide 에서 찾을 수 있습니다 .
bash 프롬프트를 표시하기 전에 명령 실행
"PROMPT_COMMAND"환경 변수에 명령을 설정하면 각 프롬프트 전에 자동으로 실행됩니다. 예:
[lsc@home]$ export PROMPT_COMMAND="date"
Fri Jun 5 15:19:18 BST 2009
[lsc@home]$ ls
file_a file_b file_c
Fri Jun 5 15:19:19 BST 2009
[lsc@home]$ ls
For the next april fools, add "export PROMPT_COMMAND=cd" to someone's .bashrc then sit back and watch the confusion unfold.
Magic key combinations from the bash man pages:
Ctrl + a and Ctrl + e move the cursor to the beginning and end of the current line, respectively.
Ctrl + t and Alt + t transpose the character and word before the cursor with the current one, then move the cursor forward.
Alt + u and Alt + l convert the current word (from the cursor to the end) to uppercase and lowercase.
Hint: Press Alt + – followed by either of these commands to convert the beginning of the current word.
Bonus man tips:
While viewing
manpages, use / to search for text within the pages. Use n to jump ahead to the next match or N for the previous match.Speed your search for a particular command or sub-section within the
manpages by taking advantage of their formatting:o Instead of typing /history expansion to find that section, try /^history, using the caret (
^) to find only lines that begin with "history."o Try / read, with a few leading spaces, to search for that builtin command. Builtins are always indented in the
manpages.
export TMOUT=$((15*60))
Terminate bash after 15 minutes of idle time, set to 0 to disable. I usually put this to ~/.bashrc on my root accounts. It's handy when administrating your boxes and you may forget to logout before walking away from the terminal.
Undo
C-S-- Control Shift Minus Undo-es typing actions.
Kill / Yank
Any delete operation C-w (delete previous word), C-k (delete to end of line), C-u (delete to start of line) etc... copies it's deleted text to the kill ring, you can paste the last kill with: C-y and cycle through (and paste from) the ring of deleted items with Alt-y
You can ignore certain files while tab completing by setting th FIGNORE variable.
For example, if you have a subverion repo and you want to navigate more easily do
export FIGNORE=".svn"
now you can cd without being blocked by .svn directories.
Using arithmetic:
if [[ $((2+1)) = $((1+2)) ]]
then echo "still ok"
fi
Brace expansion
Standard expansion with {x,y,z}:
$ echo foo{bar,baz,blam}
foobar foobaz fooblam
$ cp program.py{,.bak} # very useful with cp and mv
Sequence expansion with {x..y}:
$ echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
$ echo {a..f}{0..3}
a0 a1 a2 a3 b0 b1 b2 b3 c0 c1 c2 c3 d0 d1 d2 d3 e0 e1 e2 e3 f0 f1 f2 f3
I recently read Csh Programming Considered Harmful which contained this astounding gem:
Consider the pipeline:
A | B | C
You want to know the status of C, well, that's easy: it's in $?, or $status in csh. But if you want it from A, you're out of luck -- if you're in the csh, that is. In the Bourne shell, you can get it, although doing so is a bit tricky. Here's something I had to do where I ran dd's stderr into a grep -v pipe to get rid of the records in/out noise, but had to return the dd's exit status, not the grep's:
device=/dev/rmt8
dd_noise='^[0-9]+\+[0-9]+ records (in|out)$'
exec 3>&1
status=`((dd if=$device ibs=64k 2>&1 1>&3 3>&- 4>&-; echo $? >&4) |
egrep -v "$dd_noise" 1>&2 3>&- 4>&-) 4>&1`
exit $status;
Truncate content of a file (zeroing file)
> file
Specifically, this is very good for truncating log files, when the file is open by another process, which still may write to the file.
Not really a feature but rather a direction: I found many "hidden features", secrets and various bash usefulness at commandlinefu.com. Many of the highest rated answers to this answers, I learned them on that site :)
Another small one: Alt+#
comments out the current line and moves it into the history buffer.
So when you're assembling a command line and you need to issue an interim command to e.g. find a file, you just hit alt+#, issue the other command, go up in the history, uncomment and proceed.
Braces in lieu of do and done in for loop
For loop body are usually in do...done (just an example):
for f in *;
do
ls "$f";
done
But we can use a C style using braces:
for f in *; {
ls "$f";
}
I think this looks better than do...doneand I prefer this one. I have not yet found this in any Bash documentation, so this is really a hidden feature.
C style numeric expressions:
let x="RANDOM%2**8"
echo -n "$x = 0b"
for ((i=8; i>=0; i--)); do
let n="2**i"
if (( (x&n) == n )); then echo -n "1"
else echo -n "0"
fi
done
echo ""
These properties are another one of my favorites.
export HISTCONTROL=erasedups
export HISTSIZE=1000
The first one makes sure bash doesn't log commands more than once, will really improves history's usefulness. The other expands the history size to 1000 from the default of 100. I actually set this to 10000 on my machines.
참고URL : https://stackoverflow.com/questions/211378/hidden-features-of-bash
'IT박스' 카테고리의 다른 글
| Java를 사용하여 지정된 S3 버킷에 지정된 키가 있는지 확인하는 방법 (0) | 2020.10.25 |
|---|---|
| MySQL의 날짜 간의 월 차이 (0) | 2020.10.25 |
| Delphi XE2를 사용하는 MacOS에서 Webview가 표시되지 않음 (0) | 2020.10.25 |
| 예외가 발생하면 Akka Actor가 종료되지 않음 (0) | 2020.10.25 |
| PHP의 비동기 함수 호출 (0) | 2020.10.25 |