I've written the attached bstls.sh shell script which uses the command select to choose the subfolder or file in a folder passed as argument on which execute the ls command.

#! /bin/bash
#Personal version of shell command ls which presents to user the list of files with shell command select
#Usage: bstls.sh folder

#if parameter numbers is different from one, exit
if [ $# -ne 1 ]
then
    echo -e "Usage:\n\tbstls folder"
    exit 1
fi

PS3='Which element to ls?'
#command sed substitutes blank spaces with £ in file or folder names
#in this way user can select files or folders with blank spaces in between

list="Exit $(ls "$1" | sed 's/ /£/')"
select option in $list
do
    if [ "$option" = "Exit" ] #if user selects Exit, then exit the program
    then
        exit 0
    elif [ -n "$option" ] #if name is valid, shows the files inside
    then
        #reuse sed command to reconvert to original file name
        filename=$(echo "$option" | sed 's/£/ /')
        ls "$1"/"$filename"
    else #if the number of the choice given by user is wrong, exit
        echo "Invalid choice ($REPLY)!"
    fi
done

My main problem is how to show file names with spaces in the list of select options. For example, if I have a folder temp with the subfolder foo and the file hello world inside it, then launching the following

./bstls.sh temp  

should make me select from option

1)Exit 
2)foo 
3)hello 
4)world  

(the last two separated from each other).

Now I go to my real question. I have tried to solve this issue converting blank spaces with the symbol £ with the sed command.

list="Exit $(ls "$1" | sed 's/ /£/')"  

In this way, names with blank spaces can be processed as one by the select command.
I then change again the symbol £ with a blank space when I use ls command.

filename=$(echo "$option" | sed 's/£/ /')  

So now, when launching

./bstls.sh temp  

I get the choices

1)Exit 
2)foo
3)hello£world

Here is the question (finally): is there a way to output in the selection menu file names without that £ symbol?

up vote 7 down vote accepted

Use a shell glob instead of ls:

select option in "Exit" "$1"/*
.
.
.
elif [ -n "$option" ]; then
  ls "$option"
else
.
.
.
  • 1
    Yes! Great! As always I was lost for nothing! Thank a lot @steeldriver it worked! – Dav Serf May 24 '15 at 1:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.