Skip to content

linux下使用shell 脚本

首先确定版本,默认版本为bash

!/bin/bash

输出输入

echo,用来提示用户printf

read,用来接收回答,类似于scanf,但是不需要定义变量

bash
!/bin/bash
echo "Is it morning?Please answear yes or no."
read yes_or_no
if [ "$yes_or_no" == "yes" ]
then
echo "good morning"
else
echo "good afternoon"
fi
  1. $yes_or_no, 代表yes_or_no的值 $ 用来引用变量
  2. ==,[],if的两边都必须加空格,否则认为是同一个"东西"
  3. fi 表示if的截止

增删改查

bash
# 增删改查
# !/bin/bash
key="y"
while [ $key == "y" ]
do
echo "please input your choose 1-newfile 2-deletefie 3-editfile 4-findfile "
read ans
if [ $ans == 1 ]
then
echo "please input the file name"
read file_name
if [ -f "$file_name" ]
then
echo "the file is here"
else
touch "$file_name"
fi
else if [ $ans == 2 ]
then
echo "please input the file name"
read file_name
if [ -f "$file_name" ]
then
rm -rf $file_name
else
echo "no such file"
fi
fi
fi
if [ $ans == 3 ]
then
echo "please input the file name"
read file_name
if [ -f "$file_name" ]
then
vim $file_name
else
echo "no such file "
fi
fi
if [ $ans == 4 ]
then
echo "please input the file name"
read file_name
if [ -f "$file_name" ]
then
less $file_name
else
echo "no such file "
fi
fi
echo "if conutinue [y|n]"
read key
done

Released under the MIT License.