1.编写一个输出“Hello World”脚本

     打开文本编辑器,使用 vim命令创建并编写一个文件 test.sh,当没有test.sh文件时,vim命令会先新建test.sh文件并打开。注意:shell脚本的扩展名是 sh。

[xiaokang@localhost ~]$ vim test.sh

# 添加以下内容

#! /bin/bash
echo "Hello World !"

      #! 是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行,即使用哪一种 Shell。

      echo 命令用于向窗口输出文本。

2.运行Shell脚本

       (1)作为解释器参数来运行,这个省事,不用改权限直接运行

#  直接运行解释器,其参数就是 shell 脚本的文件名
[xiaokang@localhost ~]$ /bin/sh test.sh     
Hello World !

       (2)修改文件权限,作为可执行文件程序来运行

[xiaokang@localhost ~]$ ls -al test.sh
-rw-rw-r--   1 xiaokang xiaokang    34 Aug 23 13:43 test.sh

# 使脚本具有执行权限
[xiaokang@localhost ~]$ chmod +x ./test.sh    

[xiaokang@localhost ~]$ ls -al test.sh
-rwxrwxr-x 1 xiaokang xiaokang 34 Aug 23 13:43 test.sh

# 执行脚本,注意:./ 才能运行shell脚本
[xiaokang@localhost ~]$ ./test.sh            
Hello World !

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐