有用的 BASH 代码片段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/965663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:56:21  来源:igfitidea点击:

Useful BASH code snippets

linuxbash

提问by Nate Kohl

We've had these for a lot of other languages. The one for C/C++was quite popular, so was the equivalent for Python. I thought one for BASH would be interesting too.

我们已经为许多其他语言提供了这些。一个为C / C ++是相当普遍的,因此是为等效的Python。我认为 BASH 的一个也会很有趣。

回答by Nate Kohl

There's cd -to go to the previously-visited directory:

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

/usr/local/bin> cd /i/am/a/banana
/i/am/a/banana> cd -
/usr/local/bin>

...and then there are all those useful incarnations of the BASH for-loop:

...然后是 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

回答by Robert Gowland

In a BASH script, assign an argument to variable but provide a default if it exists:

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

MYVAR=${1:-default}

$MYVAR will contain the first argument if one was given else "default".

如果给定其他参数,则 $MYVAR 将包含第一个参数。

回答by Rob Wells

G'day,

G'day,

My favourite, and it's applicable to other shells that support aliases, is the simple way of temporarily disabling an alias by prepending a backslash to a command.

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

So:

所以:

alias rm='rm -i'

would always give you interactive mode when entering rm, entering

输入rm时总是会给你交互模式,输入

\rm

on the command line bypasses the alias.

在命令行上绕过别名。

HTH

HTH

cheers,

干杯,

回答by Fernando Martin

This is not so useful, but really interesting:

这不是很有用,但非常有趣:

history | awk '{print }' | awk 'BEGIN {FS="|"}{print }' | sort | uniq -c | sort -n | tail | sort -nr

It prints the 10 most used commands.

它打印了 10 个最常用的命令。

EDIT: This question is really similar to this.

编辑:这个问题真的很像这个

回答by Fernando Martin

Found this somewhere on the net a long time ago:

很久以前在网上的某个地方发现了这个:

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
}

回答by Paused until further notice.

Add a space (or other delimiter) only if a variable is set, in order to avoid ugly unnecessary spaces.

仅当设置了变量时才添加空格(或其他分隔符),以避免丑陋的不必要的空格。

$ first=Joe
$ last=      # last name blank, the following echoes a space before the period
$ echo "Hello, $first $last. Welcome to..."
Hello, Joe . Welcome to...

$ echo "Hello, $first${last:+ $last}. Welcome to..."
Hello, Joe. Welcome to...

$ last=Green
$ echo "Hello, $first${last:+ $last}. Welcome to..."
Hello, Joe Green. Welcome to...

回答by Paused until further notice.

To remove .svn directories you may also use the combination 'find...-prune...-exec...' (without xargs):

要删除 .svn 目录,您还可以使用组合“find...-prune...-exec...”(不带 xargs):

# tested on Mac OS X

find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -ls  # test

find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -exec /bin/rm -PRfv '{}' \; 

回答by Paused until further notice.

Here is a nice grepexpression to remove blank lines and comment lines:

这是一个grep删除空行和注释行的好表达式:

grep -v '^[ \t]*$\|^[ \t]*#' /etc/ssh/sshd_config

The above will display the used settings in sshd_configwithout any clutter.

以上将在sshd_config没有任何混乱的情况下显示使用的设置。

回答by Paused until further notice.

Here is another one:

这是另一个:

#!/bin/bash

# Shows the full path of files, good for copy pasting and for when
# listing the full paths is necessary.

# Usage: Run in the working directory (no path), otherwise takes the
# same file specification as ls.

for file in $(ls "$@"); do
        echo -n $(pwd)
        [[ $(pwd) != "/" ]] && echo -n /
        echo $file
done

回答by amarillion

At the beginning of a script that must be run as root:

在必须以 root 身份运行的脚本的开头:

if [ `id -u` != 0 ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi