Results 1 to 6 of 6

Thread: How to invoke user prompt in a shell script?

  1. #1
    Join Date
    Aug 2013
    Beans
    56

    How to invoke user prompt in a shell script?

    I tried searching for this and I didn't get the exact answer I wanted.

    Basically, what I'm trying to do is have a file copied and renamed as something else in the middle of a shell script, and the file has to be renamed according to a convention that can't be referenced against any information that's already on the computer. So I need the user to enter the information.

    What would I enter in the shell script to get the user to rename the copied file?

  2. #2
    Join Date
    Nov 2008
    Location
    Metro Boston
    Beans
    12,323
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: How to invoke user prompt in a shell script?

    How about using a command-line parameter:

    Code:
    $ script 'name_of_the_renamed_file'
    Then in the script use the positional parameter $1 to get the user's input. Have the user get in the habit of encasing the name in single quotes in case the name has embedded spaces.

    There are ways to make scripts interactive, but I've never used those.
    If you ask for help, please have the courtesy to check for responses and thank the people who helped you.

    Blog · Linode System Administration Guides · Android Apps for Ubuntu Users

  3. #3
    Join Date
    Apr 2012
    Beans
    6,947

    Re: How to invoke user prompt in a shell script?

    Do you need anything more than a simple prompt/read?

    Code:
    $ read -p "please enter a filename: " newname
    This will assign whatever the user types at the prompt to variable "$newname", which you can use as the new filename

  4. #4
    Join Date
    Aug 2013
    Beans
    56

    Re: How to invoke user prompt in a shell script?

    How would I position the "read" prompt in relation to the cp command in the script?

  5. #5
    Join Date
    Apr 2012
    Beans
    6,947

    Re: How to invoke user prompt in a shell script?

    Code:
    read -p "please enter a filename: " newname
    cp "oldfile" "$newname"
    The quotes are to allow whitespace in the names. You may want to add some checking e.g. does a file called "$newname" already exist, if so what do do etc.

  6. #6
    Join Date
    Aug 2013
    Beans
    56

    Re: How to invoke user prompt in a shell script?

    Thanks guys!

Bookmarks

Posting Permissions

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