Xxbat99xX.V.2
Xxbat99xX.V.2

Reputation: 11

linux: get a script to be able to ask the user for a file name then open that file

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?

Upvotes: 1

Views: 1714

Answers (4)

christos
christos

Reputation: 1

Write a program that asks the user to enter a file name. As much as there is no file the program is still running

Upvotes: 0

terdon
terdon

Reputation: 3380

First of all, you have an error there:

hello "welcome"

That doesn't do anything unless you have a command on your system called hello. To print a message, use

echo "welcome"

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

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

Upvotes: 1

vvvv
vvvv

Reputation: 135

Or

find . -name "<filename>" | xargs vim

Upvotes: 0

Fazlin
Fazlin

Reputation: 2337

Try to use find command. Read the man page of find command.

find <dir_name> -name ${option}

If you want to find the file and display its contents:

find <dir_name> -name ${option} | xargs cat

Upvotes: 1

Related Questions