编写脚本 Bash [英] Write a Script Bash

查看:56
本文介绍了编写脚本 Bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写一个sh文件,我想写一个脚本,输入文件夹的3个参数,文件名和文件类型.
例如,如果我有一个文件夹名称:folder_example -->[hello.txt](里面写着Hello World")
当我运行 "./example.sh folder_example hello txt" 将输出: "Hello world"
我想我需要将 readdo-while 一起使用,但我不知道确切的语法.

If I write a sh file, I want to write a script that input 3 arguments of a folder, name of a file and the type of the file.
For example, if I have a folder name: folder_example --> [hello.txt] (inside it's written "Hello World")
And when I'll run "./example.sh folder_example hello txt" will output: "Hello world"
I think I need to use read with maybe a do-while, but I don't know the exact syntax.

推荐答案

试试这个:

#/bin/bash

FOLDER_NAME=${1}
FILE_NAME=${2}
FILE_EXT=${3}

# Check folder exists

if [ ! -d "${FOLDER_NAME}" ]
then
   echo "Invalid folder name: ${FOLDER_NAME}"
   exit 1
fi

FULL_NAME="${FOLDER_NAME}/${FILE_NAME}.${FILE_EXT}"

# Check file exists

if [ ! -f "${FULL_NAME}" ]
then
   echo "Invalid file name: ${FULL_NAME}"
   exit 1
fi

# SHow file contents

echo "Contents of ${FULL_NAME}:"
cat "${FULL_NAME}" 

这篇关于编写脚本 Bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆