Linux Geek‎ > ‎

[BASH] Read command for paths

posted Nov 3, 2009 8:55 AM by Bruno Braga   [ updated Nov 3, 2009 9:12 AM ]
Today I was struggling to prepare some easy ways for converting video files (will post that later on), and came up with lots of interesting things on bash scripting. One of them is the READ command.

Besides what you can find in the man pages (note: Ubuntu 9.10 does not have the man page for this command), here are some things you may need to look into when using that:

Input paths

To have the easiness of the "tab" feature to auto-complete the path name of a file or directory, you need to set the option "-e". Strange is that you can not fully understand the power of this option just by reading the manual. Example:

    read -e -p "Type the file path: " file

Tilde on input paths

Another thing that bothered me a lot is the fact that the input value, even though is coming from the auto-complete feature from the terminal interface, is not fully understood as a path, but as a string. That means, for instance, if the path contains a tilde (~) character, the path will not be valid for a serious of operations.

For example, from the previous command (above):

    read -e -p "Type the file path: " file
    [ -f $file ] && echo "This is a file!"

If you try this with a string "/home/user/", it will work, but if you try with "~/", it will fail :-(.

The solution for that is to implement the EVAL command:

    read -e -p "Type the file path: " temp
    eval file=$temp
    [ -f $file ] && echo "This is a file!"

And voila, now it works!

 BRAGA, Bruno

 



Brazilian currently based in Japan, working on Information Technology.