shell编程入门

Posted 大数据和人工智能躺过的坑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell编程入门相关的知识,希望对你有一定的参考价值。

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

 

 技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

#!/bin/bash

echo "前进程号:"$$

echo "start"

sleep 10

kill  $$

sleep 900000000

echo "end"

 

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

这里,我就在,/下新建shell目录,用来作为shell编程的入门。

[[email protected] /]# ls

bin   data  etc   lib    lost+found  misc  net  proc  sbin     srv  tmp  var

boot  dev   home  lib64  media       mnt   opt  root  selinux  sys  usr

[[email protected] /]# mkdir shell

[[email protected] /]# ls

bin   data  etc   lib    lost+found  misc  net  proc  sbin     shell  sys  usr

boot  dev   home  lib64  media       mnt   opt  root  selinux  srv    tmp  var

[[email protected] /]# cd shell/

[[email protected] shell]# ll

total 0

[[email protected] shell]#

 

技术分享

[[email protected] shell]# ls

[[email protected] shell]# vim break1.sh

 

技术分享

[[email protected] shell]# ll

total 4

-rw-r--r--. 1 root root 79 Oct 22 09:15 break1.sh

[[email protected] shell]# chmod +x break1.sh

[[email protected] shell]# ll

total 4

-rwxr-xr-x. 1 root root 79 Oct 22 09:15 break1.sh

[[email protected] shell]# cat break1.sh    //如果变量i达到2,就跳出循环

#!/bin/bash

for ((i=0;i<10;i++))

do

if [ $i -eq 2 ]

then

break

fi

echo $i

done

[[email protected] shell]# break1.sh

-bash: break1.sh: command not found

[[email protected] shell]# ./break1.sh                  因为,此刻,还没加入到环境变量

0

1

[[email protected] shell]#

 

技术分享

[[email protected] shell]# pwd

/shell

[[email protected] shell]# vim /etc/profile

export PATH=$PATH:/shell/

 

技术分享

技术分享

[[email protected] shell]# source /etc/profile

[[email protected] shell]# break1.sh

0

1

[[email protected] shell]#

这样,就达到了。

 

技术分享

 

现在,写,while循环在外,for循环在内。

技术分享

[[email protected] shell]# ls

break1.sh  break2.sh

[[email protected] shell]# cat break2.sh

#!/bin/bash

while [ 1 -eq 1 ]

do

 

for ((i=0;i<10;i++))

do

if [ $i -eq 2 ]

then

break

fi

echo $i

done

echo ‘yes‘

sleep 1

done

[[email protected] shell]# break2.sh

0

1

yes

0

1

yes

0

1

yes

0

1

yes

^C

[[email protected] shell]#

 

技术分享

技术分享

[[email protected] shell]# cat break3.sh

#!/bin/bash

while [ 1 -eq 1 ]

do

 

for ((i=0;i<10;i++))

do

if [ $i -eq 2 ]

then

break 2              //在这里,默认是1,写个2,则说的是跳出2层循环。

fi

echo $i

done

echo ‘yes‘

sleep 1

done

[[email protected] shell]# break3.sh

0

1

[[email protected] shell]#

 

跳出单循环

for((i=0;i<10;i++))

do

echo $i

if [ $i -eq 2 ]

then

break

fi

done

 

跳出内循环

while [ 1 -eq 1 ]

do

echo ‘yes‘

sleep 1

for((i=0;i<10;i++))

do

echo $i

if [ $i -eq 2 ]

then

break

fi

done

done

 

跳出外循环

while [ 1 -eq 1 ]

do

echo ‘yes‘

sleep 1

for((i=0;i<10;i++))

do

echo $i

if [ $i -eq 2 ]

then

break 2

fi

done

done

 

技术分享

技术分享

[[email protected] shell]# cat continue.sh

#/bin/bash

for ((i=0;i<10;i++))

do

if [ $i -eq 2 ]

then

continue

fi

echo $i

done

[[email protected] shell]# continue.sh

0

1

3

4

5

6

7

8

9

[[email protected] shell]#

 

技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"

}

[[email protected] shell]# fun.sh 

 

技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"

}

test

[[email protected] shell]# fun.sh

this is a funcction

[[email protected] shell]#

 

但是,一般,生产里,也不会这么去做。

技术分享

技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"

}

[[email protected] shell]# cat funtest.sh

#!/bin/bash

source fun.sh

 

test

[[email protected] shell]# funtest.sh

this is a funcction

[[email protected] shell]#

 

         这样的好处,是fun.sh脚本,可以重用。

 技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"$1

}

[[email protected] shell]# cat funtest.sh

#!/bin/bash

source fun.sh

 

test haha

[[email protected] shell]# funtest.sh

this is a funcctionhaha

[[email protected] shell]#

 

 

 技术分享

技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"$1

}

[[email protected] shell]# cat funtest.sh

#!/bin/bash

source fun.sh

 

test $1

[[email protected] shell]# funtest.sh

this is a funcction

[[email protected] shell]# funtest.sh hehe

this is a funcctionhehe

[[email protected] shell]# funtest.sh haha hehe

this is a funcctionhaha

[[email protected] shell]# funtest.sh hahahehe

this is a funcctionhahahehe

[[email protected] shell]#

 

 

 技术分享

技术分享

[[email protected] shell]# cat fun.sh

#!/bin/bash

function test(){

 echo "this is a funcction"$1

 return 20

}

[[email protected] shell]# cat funtest.sh

#!/bin/bash

source fun.sh

 

test $1

[[email protected] shell]# funtest.sh haha

this is a funcctionhaha

[[email protected] shell]# echo $?

20

[[email protected] shell]#

 

 

 技术分享

技术分享

[[email protected] shell]# type cd

cd is a shell builtin

[[email protected] shell]# type date

date is hashed (/bin/date)

[[email protected] shell]#

 

技术分享

[[email protected] shell]# help cd

cd: cd [-L|-P] [dir]

    Change the shell working directory.

   

    Change the current directory to DIR.  The default DIR is the value of the

    HOME shell variable.

   

    The variable CDPATH defines the search path for the directory containing

    DIR.  Alternative directory names in CDPATH are separated by a colon (:).

    A null directory name is the same as the current directory.  If DIR begins

    with a slash (/), then CDPATH is not used.

   

    If the directory is not found, and the shell option `cdable_vars‘ is set,

    the word is assumed to be  a variable name.  If that variable has a value,

    its value is used for DIR.

   

    Options:

        -L      force symbolic links to be followed

        -P      use the physical directory structure without following symbolic

        links

   

    The default is to follow symbolic links, as if `-L‘ were specified.

   

    Exit Status:

    Returns 0 if the directory is changed; non-zero otherwise.

[[email protected] shell]#

 

 

技术分享

[[email protected] shell]# man date       按长空格键,翻页

DATE(1)                          User Commands                         DATE(1)

 

NAME

       date - print or set the system date and time

 

SYNOPSIS

       date [OPTION]... [+FORMAT]

       date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]

 

DESCRIPTION

       Display the current time in the given FORMAT, or set the system date.

 

       -d, --date=STRING

              display time described by STRING, not ‘now’

 

       -f, --file=DATEFILE

              like --date once for each line of DATEFILE

 

       -r, --reference=FILE

              display the last modification time of FILE

 

       -R, --rfc-2822

              output date and time in RFC 2822 format.  Example: Mon, 07 Aug 2006 12:34:56 -0600

 

       --rfc-3339=TIMESPEC

              output  date  and  time in RFC 3339 format.  TIMESPEC=‘date’, ‘seconds’, or ‘ns’ for date and time to the

              indicated precision.  Date and time components are separated by a single space: 2006-08-07 12:34:56-06:00

 

       -s, --set=STRING

              set time described by STRING

 

       -u, --utc, --universal

              print or set Coordinated Universal Time

 

       --help display this help and exit

 

:

 

 

技术分享

技术分享

[[email protected] shell]# type date
date is hashed (/bin/date)
[[email protected] shell]# man date
DATE(1) User Commands DATE(1)

NAME
date - print or set the system date and time

SYNOPSIS
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]

DESCRIPTION
Display the current time in the given FORMAT, or set the system date.

-d, --date=STRING
display time described by STRING, not ‘now’

-f, --file=DATEFILE
like --date once for each line of DATEFILE

-r, --reference=FILE
display the last modification time of FILE

-R, --rfc-2822
output date and time in RFC 2822 format. Example: Mon, 07 Aug 2006 12:34:56 -0600

--rfc-3339=TIMESPEC
output date and time in RFC 3339 format. TIMESPEC=‘date’, ‘seconds’, or ‘ns’ for date and time to the
indicated precision. Date and time components are separated by a single space: 2006-08-07 12:34:56-06:00

-s, --set=STRING
set time described by STRING

-u, --utc, --universal
print or set Coordinated Universal Time

--help display this help and exit

--version
output version information and exit

FORMAT controls the output. Interpreted sequences are:

%% a literal %

%a locale’s abbreviated weekday name (e.g., Sun)

%A locale’s full weekday name (e.g., Sunday)

%b locale’s abbreviated month name (e.g., Jan)

%B locale’s full month name (e.g., January)

%c locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)

%C century; like %Y, except omit last two digits (e.g., 20)

%d day of month (e.g, 01)

%D date; same as %m/%d/%y

%e day of month, space padded; same as %_d

%F full date; same as %Y-%m-%d

%g last two digits of year of ISO week number (see %G)

%G year of ISO week number (see %V); normally useful only with %V

%h same as %b

%H hour (00..23)

%I hour (01..12)


%j day of year (001..366)

%k hour ( 0..23)

%l hour ( 1..12)

%m month (01..12)

%M minute (00..59)

%n a newline

%N nanoseconds (000000000..999999999)

%p locale’s equivalent of either AM or PM; blank if not known

%P like %p, but lower case

%r locale’s 12-hour clock time (e.g., 11:11:04 PM)

%R 24-hour hour and minute; same as %H:%M

%s seconds since 1970-01-01 00:00:00 UTC

%S second (00..60)

%t a tab

%T time; same as %H:%M:%S

%u day of week (1..7); 1 is Monday

%U week number of year, with Sunday as first day of week (00..53)

%V ISO week number, with Monday as first day of week (01..53)

%w day of week (0..6); 0 is Sunday

%W week number of year, with Monday as first day of week (00..53)

%x locale’s date representation (e.g., 12/31/99)

%X locale’s time representation (e.g., 23:13:48)

%y last two digits of year (00..99)

%Y year

%z +hhmm numeric timezone (e.g., -0400)

%:z +hh:mm numeric timezone (e.g., -04:00)

%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)

%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)

%Z alphabetic time zone abbreviation (e.g., EDT)

By default, date pads numeric fields with zeroes. The following optional flags may follow ‘%’:

- (hyphen) do not pad the field

_ (underscore) pad with spaces

0 (zero) pad with zeros

^ use upper case if possible

# use opposite case if possible

After any flags comes an optional field width, as a decimal number; then an optional modifier, which is either E

to use the locale’s alternate representations if available, or O to use the locale’s alternate numeric symbols
if available.

DATE STRING
The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800"
or "2004-02-29 16:21:42" or even "next Thursday". A date string may contain items indicating calendar date,
time of day, time zone, day of week, relative time, relative date, and numbers. An empty string indicates the
beginning of the day. The date string format is more complex than is easily documented here but is fully
described in the info documentation.

ENVIRONMENT
TZ Specifies the timezone, unless overridden by command line parameters. If neither is specified, the set-
ting from /etc/localtime is used.

AUTHOR
Written by David MacKenzie.

REPORTING BUGS
Report date bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
Report date translation bugs to <http://translationproject.org/team/>

COPYRIGHT
Copyright ? 2010 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permit-
ted by law.

SEE ALSO
The full documentation for date is maintained as a Texinfo manual. If the info and date programs are properly
installed at your site, the command

info coreutils ‘date invocation‘

should give you access to the complete manual.

DATE STRING
The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800"
or "2004-02-29 16:21:42" or even "next Thursday". A date string may contain items indicating calendar date,
time of day, time zone, day of week, relative time, relative date, and numbers. An empty string indicates the
beginning of the day. The date string format is more complex than is easily documented here but is fully
described in the info documentation.

ENVIRONMENT
TZ Specifies the timezone, unless overridden by command line parameters. If neither is specified, the set-
ting from /etc/localtime is used.

AUTHOR
Written by David MacKenzie.

REPORTING BUGS
Report date bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
Report date translation bugs to <http://translationproject.org/team/>

COPYRIGHT
Copyright ? 2010 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permit-
ted by law.

SEE ALSO
The full documentation for date is maintained as a Texinfo manual. If the info and date programs are properly
installed at your site, the command

info coreutils ‘date invocation‘

should give you access to the complete manual.

GNU coreutils 8.4 November 2013 DATE(1)

 

 

man date对应的中文手册

date命令的帮助信息
[[email protected] source]# date --help
用法:date [选项]... [+格式]
 或:date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
以给定的格式显示当前时间,或是设置系统日期。

-d,--date=字符串 显示指定字符串所描述的时间,而非当前时间
-f,--file=日期文件 类似--date,从日期文件中按行读入时间描述
-r, --reference=文件 显示文件指定文件的最后修改时间
-R, --rfc-2822 以RFC 2822格式输出日期和时间
例如:2006年8月7日,星期一 12:34:56 -0600
--rfc-3339=TIMESPEC 以RFC 3339 格式输出日期和时间。
TIMESPEC=`date‘,`seconds‘,或 `ns‘
表示日期和时间的显示精度。
日期和时间单元由单个的空格分开:
2006-08-07 12:34:56-06:00
-s, --set=字符串 设置指定字符串来分开时间
-u, --utc, --universal 输出或者设置协调的通用时间
--help 显示此帮助信息并退出
--version 显示版本信息并退出

给定的格式FORMAT 控制着输出,解释序列如下:

%% 一个文字的 %
%a 当前locale 的星期名缩写(例如: 日,代表星期日)
%A 当前locale 的星期名全称 (如:星期日)
%b 当前locale 的月名缩写 (如:一,代表一月)
%B 当前locale 的月名全称 (如:一月)
%c 当前locale 的日期和时间 (如:2005年3月3日 星期四 23:05:25)
%C 世纪;比如 %Y,通常为省略当前年份的后两位数字(例如:20)
%d 按月计的日期(例如:01)
%D 按月计的日期;等于%m/%d/%y
%e 按月计的日期,添加空格,等于%_d
%F 完整日期格式,等价于 %Y-%m-%d
%g ISO-8601 格式年份的最后两位 (参见%G)
%G ISO-8601 格式年份 (参见%V),一般只和 %V 结合使用
%h 等于%b
%H 小时(00-23)
%I 小时(00-12)
%c 按年计的日期(001-366)
%k 时(0-23)
%l 时(1-12)
%m 月份(01-12)
%M 分(00-59)
%n 换行
%N 纳秒(000000000-999999999)
%p 当前locale 下的"上午"或者"下午",未知时输出为空
%P 与%p 类似,但是输出小写字母
%r 当前locale 下的 12 小时时钟时间 (如:11:11:04 下午)
%R 24 小时时间的时和分,等价于 %H:%M
%s 自UTC 时间 1970-01-01 00:00:00 以来所经过的秒数
%S 秒(00-60)
%t 输出制表符 Tab
%T 时间,等于%H:%M:%S
%u 星期,1 代表星期一
%U 一年中的第几周,以周日为每星期第一天(00-53)
%V ISO-8601 格式规范下的一年中第几周,以周一为每星期第一天(01-53)
%w 一星期中的第几日(0-6),0 代表周一
%W 一年中的第几周,以周一为每星期第一天(00-53)
%x 当前locale 下的日期描述 (如:12/31/99)
%X 当前locale 下的时间描述 (如:23:13:48)
%y 年份最后两位数位 (00-99)
%Y 年份
%z +hhmm 数字时区(例如,-0400)
%:z +hh:mm 数字时区(例如,-04:00)
%::z +hh:mm:ss 数字时区(例如,-04:00:00)
%:::z 数字时区带有必要的精度 (例如,-04,+05:30)
%Z 按字母表排序的时区缩写 (例如,EDT)

默认情况下,日期的数字区域以0 填充。
以下可选标记可以跟在"%"后:

- (连字符)不填充该域
_ (下划线)以空格填充
0 (数字0)以0 填充
^ 如果可能,使用大写字母
# 如果可能,使用相反的大小写

在任何标记之后还允许一个可选的域宽度指定,它是一个十进制数字。
作为一个可选的修饰声明,它可以是E,在可能的情况下使用本地环境关联的
表示方式;或者是O,在可能的情况下使用本地环境关联的数字符号。

 

 

技术分享

技术分享

[[email protected] shell]# read weekend110
aaaa
[[email protected] shell]# echo $weekend110
aaaa
[[email protected] shell]# read -p "enter your name:" name
enter your name:zhouls
[[email protected] shell]# read -s -p "enter your password:" password
enter your password:[[email protected] shell]# echo $password
sss
[[email protected] shell]# read -p "enter your name:" name
enter your name:ss
[[email protected] shell]# read -t 3 -p "enter your name:" name      3秒之后,自动
enter your name:[[email protected] shell]#

 

 

技术分享

技术分享

[[email protected] shell]# a=1+1

[[email protected] shell]# echo $a

1+1

[[email protected] shell]# declare -i a

[[email protected] shell]# a=1+1

[[email protected] shell]# echo $a

2

[[email protected] shell]# declare -r a

[[email protected] shell]# echo $a

2

[[email protected] shell]# a=3

-bash: a: readonly variable

[[email protected] shell]#

 

   declare的数组,部分,后面更新。

 

  除了使用echo $?获取函数返回值,在shell脚本里怎么获取?

答:还可以,a=$?

 

  关于有几层循环就break?

答:

[[email protected] shell]# more break2.sh
#!/bin/bash
while [ 1 -eq 1 ]
do

for ((i=0;i<10;i++))
do
if [ $i -eq 2 ]
then
break      //等价于 break 1,即退出当前for循环
fi
echo $i
done
echo ‘yes‘
sleep 1
done
[[email protected] shell]#

 

 

[[email protected] shell]# more break3.sh
#!/bin/bash
while [ 1 -eq 1 ]
do

for ((i=0;i<10;i++))
do
if [ $i -eq 2 ]
then
break 2      //跳出2循环,即先跳出for循环,再跳出while循环
fi
echo $i
done
echo ‘yes‘
sleep 1
done
[[email protected] shell]#

 

while(){ 

  for(){ 

    break

  }

}

 

 

技术分享

[[email protected] shell]# pstree
init─┬─NetworkManager
├─abrtd
├─acpid
├─atd
├─auditd───{auditd}
├─automount───4*[{automount}]
├─bonobo-activati───{bonobo-activat}
├─certmonger
├─console-kit-dae───63*[{console-kit-da}]
├─crond
├─cupsd
├─2*[dbus-daemon───{dbus-daemon}]
├─dbus-launch
├─devkit-power-da
├─gconfd-2
├─gdm-binary─┬─gdm-simple-slav─┬─Xorg
│ │ ├─gdm-session-wor
│ │ ├─gnome-session─┬─at-spi-registry
│ │ │ ├─gdm-simple-gree
│ │ │ ├─gnome-power-man
│ │ │ ├─metacity
│ │ │ ├─plymouth-log-vi
│ │ │ ├─polkit-gnome-au
│ │ │ └─{gnome-session}
│ │ └─{gdm-simple-sla}
│ └─{gdm-binary}
├─gnome-settings-───{gnome-settings}
├─gvfsd
├─hald─┬─hald-runner─┬─hald-addon-acpi
│ │ └─hald-addon-inpu
│ └─{hald}
├─master─┬─pickup
│ └─qmgr
├─5*[mingetty]
├─modem-manager
├─polkitd
├─pulseaudio───2*[{pulseaudio}]
├─rpc.statd
├─rpcbind
├─rsyslogd───3*[{rsyslogd}]
├─rtkit-daemon───2*[{rtkit-daemon}]
├─sshd───sshd───bash───bash───pstree
├─udevd───2*[udevd]
└─wpa_supplicant
[[email protected] shell]#

 

 

技术分享

[[email protected] shell]# cat a.sh
echo ‘aaa‘                  //因为系统,自带了#!/bin/bash/ ,但是,生产里,都要写,这是规范
[[email protected] shell]# a.sh
aaa
[[email protected] shell]# mv a.sh a.ss
[[email protected] shell]# a.ss      //因为,对于linux里,后缀名无关。但是,生产里,都要写,.sh结尾的后缀,这是规范
aaa
[[email protected] shell]#

 

 

 

 

参考:

Linux中执行shell脚本的4种方法总结

 























































































































































































































以上是关于shell编程入门的主要内容,如果未能解决你的问题,请参考以下文章

shell编程入门

shell编程入门

Shell 编程基础 --语法快速入门

shell编程快速入门

sehll编程入门

Shell编程入门