LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Find Shell script problem (https://www.linuxquestions.org/questions/programming-9/find-shell-script-problem-4175433719/)

9gagarmy 10-23-2012 01:38 PM

Find Shell script problem
 
I'm a newbie, I want to write a simple shell code to find a file, and if it exist vi it. But I have some problem with find command
this is the part i have problem.
Quote:

read -p "Input a name of file:" name
`find / -name $name>searchresult.txt`
$c=`head -n 1 searchresult.txt`
and the result of this code is
Quote:

=/My file location: No such of file or directory
please help me.;)

David the H. 10-23-2012 02:02 PM

First of all, please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.

1) In the bash version of read, you can use the -e option to give you readline editing. This will allow you to use tab completion and other advanced editing techniques.

2) In the second line, $(..) is highly recommended over `..`. And don't bother to use a text file; just store the result in another variable.

Although you probably have to decide what to do if the find command turns up more than one filename. Or no name.

You also need to enclose all variables in double quotes, to protect any spaces in their contents from shell word-splitting.

It's vital in scripting to understand how the shell handles arguments and whitespace:
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes


3) In the last line, you do not put $ in front of a variable when setting it, only when expanding it.


Ignoring the multiple match problem for the moment:
Code:

read -e -p "Input a name of file: " fname

fname=$( find / -type f -name "$fname" -print )        #there's probably no reason not to re-use the same variable

#you should do some other error checking here to determine if the file's legit before using it.

vi "$fname"


9gagarmy 10-23-2012 02:36 PM

thanks for helping me, I will check it.


All times are GMT -5. The time now is 05:58 PM.