Linux系统:让一个脚本可以要求用户输入一个文件名,然后打开文件 [英] linux: get a script to be able to ask the user for a file name then open that file
问题描述
我需要一个Linux脚本来询问用户是否要使用该程序,然后如果是需要问问他们想搜索的内容文件的用户。此刻,我已经创建了两个文件名为端子
和 PI
来测试我的脚本。
I need a linux script to ask the user if they want to use the program and then if yes it needs to ask the user what file they would like to search for. At the moment, I have created two files called terminal
and pi
to test my script on.
该计划的预期结果将是:
The expected outcome of the program would be:
welcome
would you like to find a file?(if yes type 'y' if no type 'n'
如果是,就应该继续追问,他们想找到那么它应该打印的文件是什么文件。
If yes, it should continue to ask what file they would like to find then it should print that file.
到目前为止,我有这样的:
So far I have this:
#!/bin/bash
hello "welcome!"
while [ "$hello" != "n" ]
do
echo "would you like to find a file?(if yes type 'y' if no type'n'"
read hello
case $hello in
y) echo "what is the name of the file?"
read option
***this is where the code i dont know should theroecticaly be***
n) echo "goodbye"
esac
done
就像我说的,预期的结果是,它会打印文件。如何才能做到这一点?
Like I said, the expected outcome is that it will print the file. How can this be done?
推荐答案
首先,你有一个错误有:
First of all, you have an error there:
hello "welcome"
除非您的系统要求有一个命令,并不做任何事情你好
。要打印邮件,请使用
echo "welcome"
要打印一个消息后得到用户的输入,使用读
。由于您使用庆典
,您可以使用 -p
选项present一条消息,并保存用户一个命令输入:
To get input from the user after printing a message, use read
. Since you're using bash
, you can use the -p
option to present a message and save user input with one command:
read -p message" variable
要查找并显示文件的内容,你可以使用找到
命令和 -exec
选项。例如, -exec少
使用显示文件少
。
To find and display the contents of the file, you can use the find
command and its -exec
option. For example, -exec less
to display the file using less
.
然后,您有其他各种错误。脚本的工作版本会是这样的:
Then, you have various other errors. A working version of your script would be something like:
#!/usr/bin/env bash
echo 'Welcome!'
while [ "$response" != "n" ]
do
read -p "Would you like to find a file? [y/n]:" response
case $response in
y) read -p "What is the name of the file? " file
find . -type f -name "$file" -exec less {} \;
;;
n)
echo "goodbye"
exit ;;
esac
done
这篇关于Linux系统:让一个脚本可以要求用户输入一个文件名,然后打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!