有用的BASH代码片段

15 linux bash

我们已经有很多其他语言了.用于C/C++的那个很受欢迎,因此与Python相当.我认为BASH的一个也很有意思.

Nat*_*ohl 18

cd -去以前访问过的目录:

/usr/local/bin> cd /i/am/a/banana
/i/am/a/banana> cd -
/usr/local/bin>
Run Code Online (Sandbox Code Playgroud)

......然后有BASH for循环的所有有用的化身:

for file in *.txt; do ls $file; done

for item in $(echo foo bar baz); do echo $item; done

for num in {0..9}; do echo $num; done
Run Code Online (Sandbox Code Playgroud)

  • 我从来不知道`cd -`,谢谢!看起来它可能有所帮助. (2认同)
  • ick ...我总是讨厌看到`seq ij`和`jot ji`.现代bash有范围扩展:对于{1..100}中的n; 做...... (2认同)
  • 为什么你有一个名为/ i/am/a/banana的目录?;) (2认同)

Rob*_*and 14

在BASH脚本中,为变量分配参数,但如果存在,则提供默认值:

MYVAR=${1:-default}
Run Code Online (Sandbox Code Playgroud)

$ MYVAR将包含第一个参数,如果给出一个"默认".


Rob*_*lls 11

天儿真好,

我最喜欢的,它适用于支持别名的其他shell,是通过在命令前加一个反斜杠来暂时禁用别名的简单方法.

所以:

alias rm='rm -i'
Run Code Online (Sandbox Code Playgroud)

输入rm时输入将始终为您提供交互模式

\rm
Run Code Online (Sandbox Code Playgroud)

在命令行上绕过别名.

HTH

干杯,


Fer*_*tin 6

这不是很有用,但真的很有趣:

history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -n | tail | sort -nr
Run Code Online (Sandbox Code Playgroud)

它打印10个最常用的命令.

编辑:这个问题与非常相似.


小智 5

很久以前在网上找到了这个:

function bashtips {
cat <<EOF
DIRECTORIES
-----------
~-      Previous working directory
pushd tmp   Push tmp && cd tmp
popd        Pop && cd

GLOBBING AND OUTPUT SUBSTITUTION
--------------------------------
ls a[b-dx]e Globs abe, ace, ade, axe
ls a{c,bl}e Globs ace, able
\$(ls)      \`ls\` (but nestable!)

HISTORY MANIPULATION
--------------------
!!      Last command
!?foo       Last command containing \`foo'
^foo^bar^   Last command containing \`foo', but substitute \`bar'
!!:0        Last command word
!!:^        Last command's first argument
!\$     Last command's last argument
!!:*        Last command's arguments
!!:x-y      Arguments x to y of last command
C-s     search forwards in history
C-r     search backwards in history

LINE EDITING
------------
M-d     kill to end of word
C-w     kill to beginning of word
C-k     kill to end of line
C-u     kill to beginning of line
M-r     revert all modifications to current line
C-]     search forwards in line
M-C-]       search backwards in line
C-t     transpose characters
M-t     transpose words
M-u     uppercase word
M-l     lowercase word
M-c     capitalize word

COMPLETION
----------
M-/     complete filename
M-~     complete user name
M-@     complete host name
M-\$        complete variable name
M-!     complete command name
M-^     complete history
EOF
}
Run Code Online (Sandbox Code Playgroud)


小智 0

为了将~中由vboxusers组拥有的所有文件更改为由用户组 kent 拥有,我创建了一些内容。但由于它在使用 xargs 方面存在弱点,我将其更改为对此答案的评论中提出的解决方案:

$ find ~ -group vboxusers -exec chown kent:kent {} \;
Run Code Online (Sandbox Code Playgroud)