Shell编程----Expect免交互

Shell编程----Expect免交互&标记法免交互

前言

一: Here Document 免交互

1.1:什么是Here Document?

  • Here document (here-document, here-text, heredoc, hereis, here-string, here-script)是一个文件文字或输入流文字:它是源代码文件的一部分,被视为它是一个单独的文件。该术语还用于使用类似语法,保留换行符和文本中的其他空格(包括缩进)的多行字符串文字形式。

1.2: Here Document 概述

  • 使用I/O重定向的方式将命令列表提供给交互程序

  • 标准输入的一种替代品

  • 语法格式

    命令 <<标记
    ...
    ...
    标记
    

1.3: Here Document 使用注意事项

  • 标记可以使用任意合法字符
  • 结尾的标记一定要顶格写,前面不能有任何字符
  • 结尾的标记后面也不能有任何字符(包括空格)
  • 开头标记前后的空格会被省略掉

1.4: Here Document免交互

  • 通过read 命令接受输入并打印

    [root@shell ~]# vim b.sh
    #!/bin/bash
    read i <<EOF
    hello world
    my name is zhangsan
    EOF
    echo $i
    [root@shell ~]# chmod +x b.sh 
    [root@shell ~]# ./b.sh 
    hello world
    
  • 通过paswd给用户设置密码

    [root@shell ~]# vim passwd.sh
    #!/bin/bash
    useradd zhangsan
    passwd zhangsan <<EOF
    abc123
    abc123
    EOF
    [root@shell ~]# chmod +x passwd.sh 
    [root@shell ~]# ./passwd.sh 
    更改用户 zhangsan 的密码 。
    新的 密码:无效的密码: 密码少于 7 个字符
    重新输入新的 密码:passwd:所有的身份验证令牌已经成功更新。
    

1.5: Here Document 变量设定

  • 变量替换

    [root@shell ~]# vim filename.sh
    #!/bin/bash
    filename="test.txt"
    school="kgc"
    cat > $filename <<EOF
    this is $school .com
    EOF
    [root@shell ~]# chmod +x filename.sh 
    [root@shell ~]# ./filename.sh 
    [root@shell ~]# ls
     test.txt
     .....
    [root@shell ~]# cat test.txt 
    this is kgc .com
    
  • 变量设定

    [root@localhost ~]# vim here_var_set.sh
    #!/bin/bash
    ivar="Great! Beautyful!"
    myvar=$(cat <<EOF
    This is Line 1.
    That are Sun,Moon and Stars.
    $ivar
    EOF 
    )
    echo $myvar
    [root@localhost ~]# sh here_var_set.sh
    This is Line 1. That are Sun,Moon and Stars. Great! Beautyful!
    

1.6: Here Document 格式控制

  • 关闭变量替换功能

    [root@localhost ~]# cat here_format_shut.sh
    #!/bin/bash
    cat <<'EOF'                       #单引号关闭变量替换
    This is Line 1.
    $kgc
    EOF
    [root@localhost ~]# sh here_format_shut.sh
    This is Line 1.
    $kgc                              #变量当成普通字符输出
    
  • 去除每行之前的TAB字符

    [root@localhost ~]# vim here_format_tab.sh
    #!/bin/bash
    cat <<-
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值