Find the answer to your Linux question:
Results 1 to 3 of 3
I'm trying to call a specific variable based on a user selection. For example: Code: Select a file: [1] foo.tar [2] bar.tar Enter a selection: I have already coded each ...
  1. #1
    Just Joined!
    Join Date
    May 2011
    Posts
    1

    Bash - Calling a specific variable based on user input

    I'm trying to call a specific variable based on a user selection. For example:

    Code:
    Select a file:
    [1] foo.tar
    [2] bar.tar
    
    Enter a selection:
    I have already coded each possible selection to have its own variable. If the user selects 2 I need to select $SELECTED_TAR2, or if they select 1 I need to select $SELECTED_TAR1 and then do something like this behind the scenes:

    Code:
    cp /home/user/$SELECTED_TAR2 /home/user/backup/$SELECTED_TAR2
    I was thinking something like this:

    Code:
    echo "Enter a selection: "
    read -e SELECTED_NUMBER
    cp /home/user/$SELECTED_TAR$SELECTED_NUMBER /home/user/backup/$SELECTED_TAR$SELECTED_NUMBER
    I'm used to Ruby and you would accomplish something like that this way:

    Code:
    cp /home/user/SELECTED_TAR"#{SELECTED_NUMBER}" /home/user/backup/SELECTED_TAR"#{SELECTED_NUMBER}"
    Any ideas?

  2. #2
    Just Joined!
    Join Date
    Mar 2011
    Location
    pittsburgh
    Posts
    44
    You could use if statements
    Code:
    echo "make a selection:"
    echo "[1]file.one [2]file.two [3]file.three"
    read INPUT
    
    if [$INPUT -eq 1]
    then
    cp /home/file.one /home/backup/file.one
    fi
    
    if [$INPUT -eq 2]
    then
    cp /home/file.two /home/backup/file/two
    fi
    
    if [$INPUT -eq 3]
    then
    cp /home/file.three /home/backup/file.three
    fi
    EDIT:
    This is just a general idea, you can still use the variables you made in the paths, I just wanted to show you how you can use if statements to make a decision based on user input.

  3. #3
    Just Joined!
    Join Date
    Sep 2010
    Posts
    5
    It looks like you want to let the user select which file in a directory.. you can try something like this:

    Code:
    someDir=/directory/of/files
    
    for i in $( ls $someDir | sort ); do
      echo ${n}. ${i}
      echo ${i} >> $someDir/tmp.list
      n=$(($n+1))
    done
    
    echo ${n}. Exit $( basename $0 )
    echo -n Please choose a number:
    read userChoice
    
    if [ $userChoice -eq $n ]; then
      exit
    else
      selectedFile=`sed -n "${n}{p;q;}" $someDir/tmp.list`
      # do your work with the selected file here
    fi
    
    rm $someDir/tmp.list

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...