Linux初涉shell脚本

    xiaoxiao2021-03-25  104

    1.创建shell脚本

    1)文件的第一行应为:

    #!/bin/bash ##默认执行环境为/bin/bash

    2) chmod +x file.sh ##使文件可执行

    3)脚本调试

    sh -x file.sh

    2.基本概念

    1)引用与转义

    强引用 ’ ’ 单引号:将字符串放置在单引号中,保留字符串中所有字符的文字值,同时禁用所有扩展. 弱引用 ” ” 双引号:将字符串放置在双引号中,变量扩展和命令扩展在双引号内仍起作用. 转义 \ 反斜线:非引用的\是转义字符.它保留了下一个字符的文字值.

    2)Shell变量

    shell变量用于为稍后在脚本中使用的名称指定值,并且仅限于shell命令行或从中声明变量的脚本,常用大写表示.使用时变量前加$. 例子:

    #!/bin/bash NAME=yang echo name is $NAME

    3)算术运算符

    ++ ##增量后 -- ##减量后 - ##减法 + ##加法 ** ##幂运算 * ##乘法 / ##除法 % ##余数 += ##加等 -= ##减等

    4)循环语句

    for语句

    for N in $(seq 1 2 10 ) ##1-10间隔为2 do echo "$N" done 用(())表示数学运算. #!/bin/bash for ((i=1;i<10;i++)) do ((j+=i)) done echo $j

    5)选择分支语句

    if语句

    #!/bin/bash if [ 1 > 0 ] then echo 1 else echo 0 fi [root@server mnt]# sh shell.sh 1

    case语句

    #!/bin/bash case "$1" in 1) echo This is 1 ;; 2) echo This is 2 ;; *) echo NOT 1 OR 2 ;; esac [root@server mnt]# sh shell.sh 1 This is 1 [root@server mnt]# sh shell.sh 12 NOT 1 OR 2 [root@server mnt]# sh shell.sh 2 This is 2

    6)交互式输入

    read提示用户输入(使用-p选项)并将其直接存储到一个或多个变量

    #!/bin/bash read -p "please input:" WORD echo word is $WORD [root@server mnt]# sh shell.sh 2 please input:yang word is yang

    使用位置参数来读取传递给脚本的命令行参数或选项输入。各种特殊变量存储传递的选项编号

    指定的位置参数总数:$# 位置参数自身:$0、$1、$2、$3.... 所有位置参数: $@、$*

    7)退出状态

    grep的退出状态的含义: 0 – 在指定的文件中找到了模式 1 – 在指定的文件中未找到模式 >1 – 一些其他错误(无法打开文件、错误的搜索表达式等) [root@server mnt]# cat /mnt/shell.sh >& /dev/null [root@server mnt]# echo $? 0 [root@server mnt]# cat /mnt/shell.s >& /dev/null [root@server mnt]# echo $? 1

    8)自动应答

    yum install expect.x86_64 -y ##自动应答脚本所需软件 vim /mnt/ssh

    read -p "please user" -s USER read -p "please IP" -s IP ssh ${USER}@${IP}

    vim /mnt/answer.exp

    #!/usr/bin/expect set USER [ lindex $argv 0 ] set PASSWD [ lindex $argv 1 ] set IP [ lindex $argv 2 ] spawn /mnt/ssh expect { "please user" { send "$USER\r"; exp_continue } "yes" { send "yes"; exp_continue } "please IP" { send "$IP\r"; exp_continue } "password" { send "$PASSWD\r"; exp_continue } expect eof } [root@server mnt]# /mnt/answer.exp root westos 172.25.254.62 spawn /mnt/ssh please userplease IProot@172.25.254.62's password: Last login: Thu Mar 9 16:54:56 2017 from 172.25.254.10 [root@yang ~]#

    9)环境变量

    shell和脚本使用变量来存储数据 ,有些变量可以连同它们的内容传递给子进程,这些变量我们称之为环境变量. export ##环境级 vim ~/.bash_profile ; source .bash_profile ##用户级 vim /etc/profile ; source /etc/profile ##系统级

    转载请注明原文地址: https://ju.6miu.com/read-14155.html

    最新回复(0)