bash编程快速入门

#!/bin/bash
# First line of the script is shebang which tells the system how to execute
# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured, comments start with #. Shebang is also a comment.


# 特别提示一下,# => 代表的是命令的输出



# bash版本的Hello World
echo Hello world! # => Hello world!

# 一行一般只放一组指令,如果想在一行中放多组指令需要用分号“ ; ” 隔开
echo 'This is the first line'; echo 'This is the second line'
# => This is the first line
# => This is the second line

# 声明一个变量:
Variable="Some string"

# 声明变量时,等号两边不能有空格:
Variable = "Some string" # => returns error "Variable: command not found"
#如果声明变量时 左右两边有空格,bash会把他当成一个可执行的命令,并返回一个'command not found'的错误

# 也不能单独右边有空格:
Variable= 'Some string' # => returns error: "Some string: command not found"
# 如果声明变量时,单独右边有空格,bash会把他当成一个可执行的命令,并返回一个'command not found'的错误.
# 但是如果字符串中为有效的命令,则会执行字符串中的命令,比如Variable= "ls"这种情况就会列出当前目录下的文件

# 调用一个变量:
echo $Variable # => Some string
echo "$Variable" # => Some string
echo '$Variable' # => $Variable
# Note that ' (single quote) won't expand the variables!
# 声明变量的时候不需要在前面加$,调用变量时才需要。


# 另一种调用变量的方式 ${ }:
echo ${Variable} # => Some string
# This is a simple usage of parameter expansion
# Parameter Expansion gets a value from a variable.  It "expands" or prints the value
# During the expansion time the value or parameter are able to be modified
# Below are other modifications that add onto this expansion
# 这是变量拓展的一种简单用法
# 变量

# 替换变量中的字符
echo ${Variable/Some/A} # => A string
# 将字符串中第一个 “Some” 替换为 “A”

# 截取变量中的字符
Length=7
echo ${Variable:0:Length} # => Some st
# 截取变量的前7个字符

————————————————————————
# Default value for variable
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} 
# => DefaultValueIfFooIsMissingOrEmpty
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.

# 声明一个带有6个元素的数组
array=(one two three four five six)
# 输出数组第一个元素
echo $array # => "one"
# 另一种输出第一个元素的方式
echo ${array[0]} # => "one"
# 输出所有元素
echo ${array[@]} # => "one two three four five six"
# 输出数组元素个数
echo ${#array[@]} # => "6"
#输出第三个元素的字符长度
echo ${#array0[2]} # => "5"
# 输出从第四个元素开始的,两个元素
echo ${array[@]:3:2} # => "four five"

#输出所有元素,每一行一个
for i in "${array0[@]}"; do
    echo "$i"
done

# Brace Expansion { }
# 大括号扩展 { },通常用于生成任意字符串
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
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


# Builtin variables:
# 预定义变量:
# There are some useful builtin variables, like
# 系统预定义了一些有用的变量,如$?代表上一个程序的返回值
echo "Last program's return value: $?"

# $$代表进程的PID
echo "Script's PID: $$"
# $#代表位置参数的个数
echo "Number of arguments passed to script: $#"

# 所有传入的位置参数
echo "All arguments passed to script: $@"

# 对应的位置参数
echo "Script's arguments separated into different variables: $1 $2..."

# Now that we know how to echo and use variables,
# let's learn some of the other basics of bash!
# 我们已经知道如何输出和使用变量,现在学习一些其他的bash基础


# 可以通过`pwd`显示当前目录的路径
# `pwd` 是 "print working directory"缩写,翻译过来就是:输出当前目录
# We can also use the builtin variable `$PWD`.
# 我们也可以用预定义的变量 ‘$PWD'达到同样的效果
# 下面两个方式都是等价的,同样是输出当前目录
echo "I'm in $(pwd)" # execs `pwd` and interpolates output
echo "I'm in $PWD" # interpolates the variable


# 如果你嫌弃终端上输出太多的东西,可以用`clear`来清屏
clear
#用 ctrl-L 快捷键也可以达到同样的效果

# 通过输入来赋值,read 命令将读取用户的输入并将值赋给变量
echo "What's your name?"
read Name # 注意我们不需要从新定义新的变量,read命令会读取用户的输入并将值赋给变量
echo Hello, $Name!


# if 结构
# 可以输入 ’man test‘ 来查看更多有关条件测试的内容
if [ $Name != $USER ]
then
    echo "Your name isn't your username"
else
    echo "Your name is your username"
fi
# 如果变量$Name等于当前用户登录名,则为真 

# NOTE: if $Name is empty, bash sees the above condition as:
# 注意: 如果 $Name 为空,bash 会将条件判断视为以下测试条件:
if [ != $USER ]
# 这是将会出现语法错误的,所以更安全的方式就是,将引用的变量包含在一个字符串中
if [ "$Name" != $USER ] ...
# which, when $Name is empty, is seen by bash as:
# 当变量为空时,bash将他设为一个空的字符串
if [ "" != $USER ] ...
# which works as expected


# 除了有条件测试以外,还有条件执行
# ||代表逻辑“或”,表示当第一个命令执行失败,再执行第二个命令
echo "Always executed" || echo "Only executed if first command fails"
# => Always executed
# &&代表逻辑"与",表示当第一个命令执行成功,再执行第二个命令
echo "Always executed" && echo "Only executed if first command does NOT fail"
# => Always executed



# To use && and || with if statements, you need multiple pairs of square brackets:
# 也可以在条件测试中,使用&&和||
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
    echo "This will run if $Name is Steve AND $Age is 15."
fi

if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
    echo "This will run if $Name is Daniya OR Zach."
fi

# Redefine command 'ping' as alias to send only 5 packets
alias ping='ping -c 5'
# Escape alias and use command with this name instead
\ping 192.168.1.1
# Print all aliases
alias -p

# Expressions are denoted with the following format:
# 加减乘除运算需要用双括号包起来
echo $(( 10 + 5 )) # => 15

# Unlike other programming languages, bash is a shell so it works in the context
# of a current directory. You can list files and directories in the current
# directory with the ls command:
# 与其他编程语言不同的是,bash还是一个命令终端(shell),所以还可以使用一些系统命令,比如用ls来显示当前目录的内容
ls # Lists the files and subdirectories contained in the current directory
   # 列出当前目录的子目录和文件

# These commands have options that control their execution:
# 还可以在 ls 命令后添加一些选项来执行
ls -l # Lists every file and directory on a separate line
      # 在每一行中分别列出每个文件和目录的信息
ls -t # Sorts the directory contents by last-modified date (descending)
      # 通过修改时间来排序
ls -R # Recursively `ls` this directory and all of its subdirectories
      # 递归的方式显示当前目录下的所有子目录
# Results of the previous command can be passed to the next command as input.
# grep command filters the input with provided patterns. That's how we can list
# .txt files in the current directory:
ls -l | grep "\.txt"

# Use `cat` to print files to stdout:
cat file.txt

# We can also read the file using `cat`:
Contents=$(cat file.txt)
echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character
# => START OF FILE
# => [contents of file.txt]
# => END OF FILE

# Use `cp` to copy files or directories from one place to another.
# `cp` creates NEW versions of the sources,
# so editing the copy won't affect the original (and vice versa).
# Note that it will overwrite the destination if it already exists.
cp srcFile.txt clone.txt
cp -r srcDirectory/ dst/ # recursively copy

# Look into `scp` or `sftp` if you plan on exchanging files between computers.
# `scp` behaves very similarly to `cp`.
# `sftp` is more interactive.

# Use `mv` to move files or directories from one place to another.
# `mv` is similar to `cp`, but it deletes the source.
# `mv` is also useful for renaming files!
mv s0urc3.txt dst.txt # sorry, l33t hackers...

# Since bash works in the context of a current directory, you might want to 
# run your command in some other directory. We have cd for changing location:
cd ~    # change to home directory
cd ..   # go up one directory
        # (^^say, from /home/username/Downloads to /home/username)
cd /home/username/Documents   # change to specified directory
cd ~/Documents/..    # still in home directory..isn't it??

# Use subshells to work across directories
(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD")
pwd # still in first directory

# Use `mkdir` to create new directories.
mkdir myNewDir
# The `-p` flag causes new intermediate directories to be created as necessary.
mkdir -p myNewDir/with/intermediate/directories
# if the intermediate directories didn't already exist, running the above
# command without the `-p` flag would return an error

# You can redirect command input and output (stdin, stdout, and stderr).
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
# between "EOF":
cat > hello.py << EOF
#!/usr/bin/env python
from __future__ import print_function
import sys
print("#stdout", file=sys.stdout)
print("#stderr", file=sys.stderr)
for line in sys.stdin:
    print(line, file=sys.stdout)
EOF

# Run the hello.py Python script with various stdin, stdout, and 
# stderr redirections:
python hello.py < "input.in" # pass input.in as input to the script
python hello.py > "output.out" # redirect output from the script to output.out
python hello.py 2> "error.err" # redirect error output to error.err
python hello.py > "output-and-error.log" 2>&1 # redirect both output and errors to output-and-error.log
python hello.py > /dev/null 2>&1 # redirect all output and errors to the black hole, /dev/null, i.e., no output
# The output error will overwrite the file if it exists,
# if you want to append instead, use ">>":
python hello.py >> "output.out" 2>> "error.err"

# Overwrite output.out, append to error.err, and count lines:
info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
wc -l output.out error.err

# Run a command and print its file descriptor (e.g. /dev/fd/123)
# see: man fd
echo <(echo "#helloworld")

# Overwrite output.out with "#helloworld":
cat > output.out <(echo "#helloworld")
echo "#helloworld" > output.out
echo "#helloworld" | cat > output.out
echo "#helloworld" | tee output.out >/dev/null

# Cleanup temporary files verbosely (add '-i' for interactive)
# WARNING: `rm` commands cannot be undone
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively delete

# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
# current directory.
echo "There are $(ls | wc -l) items here."

# The same can be done using backticks `` but they can't be nested - the preferred way
# is to use $( ).
echo "There are `ls | wc -l` items here."

# Bash uses a case statement that works similarly to switch in Java and C++:
case "$Variable" in
    #List patterns for the conditions you want to meet
    0) echo "There is a zero.";;
    1) echo "There is a one.";;
    *) echo "It is not null.";;
esac

# for loops iterate for as many arguments given:
# The contents of $Variable is printed three times.
for Variable in {1..3}
do
    echo "$Variable"
done
# => 1
# => 2
# => 3


# Or write it the "traditional for loop" way:
for ((a=1; a <= 3; a++))
do
    echo $a
done
# => 1
# => 2
# => 3

# They can also be used to act on files..
# This will run the command 'cat' on file1 and file2
for Variable in file1 file2
do
    cat "$Variable"
done

# ..or the output from a command
# This will cat the output from ls.
for Output in $(ls)
do
    cat "$Output"
done

# while loop:
while [ true ]
do
    echo "loop body here..."
    break
done
# => loop body here...

# You can also define functions
# Definition:
function foo ()
{
    echo "Arguments work just like script arguments: $@"
    echo "And: $1 $2..."
    echo "This is a function"
    return 0
}
# Call the function `foo` with two arguments, arg1 and arg2:
foo arg1 arg2
# => Arguments work just like script arguments: arg1 arg2
# => And: arg1 arg2...
# => This is a function

# or simply
bar ()
{
    echo "Another way to declare functions!"
    return 0
}
# Call the function `bar` with no arguments:
bar # => Another way to declare functions!

# Calling your function
foo "My name is" $Name

# There are a lot of useful commands you should learn:
# prints last 10 lines of file.txt
tail -n 10 file.txt

# prints first 10 lines of file.txt
head -n 10 file.txt

# sort file.txt's lines
sort file.txt

# report or omit repeated lines, with -d it reports them
uniq -d file.txt

# prints only the first column before the ',' character
cut -d ',' -f 1 file.txt

# replaces every occurrence of 'okay' with 'great' in file.txt
# (regex compatible)
sed -i 's/okay/great/g' file.txt

# print to stdout all lines of file.txt which match some regex
# The example prints lines which begin with "foo" and end in "bar"
grep "^foo.*bar$" file.txt

# pass the option "-c" to instead print the number of lines matching the regex
grep -c "^foo.*bar$" file.txt

# Other useful options are:
grep -r "^foo.*bar$" someDir/ # recursively `grep`
grep -n "^foo.*bar$" file.txt # give line numbers
grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files

# perform the same initial search, but filter out the lines containing "baz"
grep "^foo.*bar$" file.txt | grep -v "baz"

# if you literally want to search for the string,
# and not the regex, use fgrep (or grep -F)
fgrep "foobar" file.txt

# The trap command allows you to execute a command whenever your script 
# receives a signal. Here, trap will execute `rm` if it receives any of the 
# three listed signals.
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM

# `sudo` is used to perform commands as the superuser
# `sudo` 是以管理员用户权限执行
NAME1=$(whoami)
NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"

# Read Bash shell builtins documentation with the bash 'help' builtin:
help
help help
help for
help return
help source
help .

# Read Bash manpage documentation with man
apropos bash
man 1 bash
man bash

# Read info documentation with info (? for help)
apropos info | grep '^info.*('
man info
info info
info 5 info

# Read bash info documentation:
# 查看bash 文档
info bash
info bash 'Bash Features'
info bash 6
info --apropos bash

 

本文翻译与一个叫 “ learxinyminutes ”网站中的一个帖子,并根据自己的理解更改了一些注释,(似乎有些脱离作者的原意,因为我觉得有些注释似乎过于啰嗦,快速入门系列应该抱着 “能简则简” 的原则,所有有些注释就直接删除了,没照搬直译过来)。

我也是初学bash编程,英语水平也很一般(没过四级),翻译得不好的地方还望见谅。之所以想到翻译这篇文章的目的是想通过这种方式加深对bash语法的记忆,如果我 “ 翻译 ” 的这篇文章能帮到你就更好了。原文链接在点这里

转载于:https://my.oschina.net/u/3785630/blog/1793455

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值