您的位置:首页 > 运维架构 > Shell

常用shell命令总结

2015-01-12 09:50 621 查看

Shell 常用命令

这篇博客记录了一些 Shell 常用命令 供未来查阅。

添加ll

为了简化 “ls -l”,可以在
~/.bash_profile
中加入:

12alias ll='ls -l'

获得参数

$0
是命令本身
$1
是第一个参数

$

$可以认为是 获取内容 。

内置变量

bash有很多内置变量,我们可以使用
$
获取到它们,例如:

1

2

3

4

5

$PWD

$HOME

$PATH

$(pwd)

读取配置

配置数据可以像下面一样:

1234Fansy:UtilTools fansy$ cat .meta Installed=FalseVersion=1.0
写在一个文件中。当读取它的内容时,可以加入如下代码:

1

2

3

4

5

6

configPath=.meta;

source
$configPath;

echo
$Installed;

echo
$Version;

更改配置

使用
sed
来替换配置文件中的内容,在上面的例子中,我可以更改配置文件中的值为True :

12sed -i $configPath 's/^Installed.*/Installed=True/g' $configPath
's/aaa/bbb/g' file.txt
是将aaa替换为bbb,这里使用正则表达式,匹配以 “Installed” 开始的行。-i 意味着 替换源文件,否则只在内存中做替换,无法保存。

写入文件 重定向

1

2

3

4

>
输出重定向

>>
追加到输出重定向

<
输入重定向

<<
追加到输入重定向

因此在文件末尾添加内容可以使用:

1echo "something" >> file.txt

#!/bin/bash

它叫做 shebang, 它告诉shell执行时的程序类型,例如:

1

2

3

4

5

6

7

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible
shell

#!/bin/csh — Execute the file using csh, the C shell, or a compatible
shell

#!/usr/bin/perl -T — Execute using Perl with the option for taint checks

#!/usr/bin/php — Execute the file using the PHP command line interpreter

#!/usr/bin/python -O — Execute using Python with optimizations to code

#!/usr/bin/ruby — Execute using Ruby

echo

使用
-e
可以格式化输出字符串。

条件测试

[ condition ]
可以测试一个表达式。
$?
可以获取判断结果,0表示condition=true.

12345ln -s $fullpath $linkpath;if [ $? -eq 0 ]; then echo "link success";fi

字符串比较

= 两字符串相等
!= 两字符串不等
-z 空串 [zero]
-n 非空串 [nozero]

1

2

3

4

[
-z
"$EDITOR"
]

[
"$EDITOR"
=
"vi"
]

[
"$1"x
=
""x
]
#for empty parameter

数字比较

123456789-eq 数值相等(equal)-ne 不等(not equal)-gt A>B(greater than)-lt A<B(less than)-le A<=B(less、equal)-ge A>=B(greater、equal) N=130[ "$N" -eq 130 ]

if-else

1

2

3

4

5

6

7

8

9

10

if
condition1

then

//do
thing a

elif
condition2

then

//do
thing b

else

//do
thing c

fi

or

1234if condition; then # do somethingfi

函数

定义:

1

2

3

4

5

6

7

8

function
func_name()
{

}

func_name()
{

//do
some thing

}

传递参数:

123456789function copyfile() { cp $1 $2 return $?} copyfile /tmp/a /tmp/borresult=`copyfile /tmp/a /tmp/b`

搜索匹配

判断文件中是否含有某个字符串:

1

2

3

4

5

6

if
grep
-q
"$Text"
$file;
then

echo
"Text found";

else

echo
"No Text";

fi

字符串处理

使用
${expression}


12345${parameter:-word}${parameter:=word}${parameter:?word}${parameter:+word}
上面4种可以用来进行缺省值的替换。

1

2

${#parameter}

上面这种可以获得字符串的长度。

12345${parameter%word} 最小限度从后面截取word${parameter%%word} 最大限度从后面截取word${parameter#word} 最小限度从前面截取word${parameter##word} 最大限度从前面截取word
详细使用可以参考这个

ln 软连接

使用软连接可以直接执行一个程序。命令为:

1

2

ln
-s
source_file
target_file

其中 source_file 要写绝对路径。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: