简体   繁体   中英

bash shell script automaticall add on file extension

Hello so today i was playing around with my shell script and figured to make it more user friendly i would make it so the file extension of file was automatically added.

for example say the user wants to search a file using grep but first they must type in thhe name of the file in this case lets say file.txt what i want to do is automatically add on the .txt so the user only needs to type in "file"

here is what i have so far but this does not work:

echo "Current .txt files "
        ls -R |grep .txt
        echo "--------------------------------------------------------------------------------"
                echo -n "Please select a file to search in: "
                read fileName
                file=$fileName.txt

i thought in this case since i am appending an extension on to the end of the variable name but this has not worked.

Put quotes around it:

file="$filename.txt"

EDIT: As it happens, this answer is incorrect. See the comments below and the other answer.

Your code should work. See below-

Contents of test.sh :

#!/bin/bash

echo "Current .txt files "
        ls -R |grep .txt
        echo "--------------------------------------------------------------------------------"
                echo -n "Please select a file to search in: "
                read fileName
                file=$fileName.txt

echo "You are searching for $file"
ls -l "$file"

Test run:

$ ./test.sh
Current .txt files
p1.txt
t1.txt
t2.txt
--------------------------------------------------------------------------------
Please select a file to search in: t2
You are searching for t2.txt
-rw-r----- 1 d1rld1f1 d1rld1f1 4 Apr 20 12:41 t2.txt
$

BTW, it is generally advisable to enclose variable names in double quotes. This prevents reinterpretation of all special characters within the quoted string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM