0

This is my first post here. I have only dabbled in python on Udemy and I know some HTML and CSS but decided to give BASH a go tonight. I am trying to write a simple script using a variable and it is not working. The script should print some text, ask for some user input, then use that input in a subsequent command like so:

#!bin/bash

echo "Please select a name for your new file (files are saved in txt by default)": && read $file
echo "Creating file "$file".txt on /home/linux/Desktop"
touch "/home/linux/Desktop/"$file".txt"
echo "Your new file has been created."
sleep 2
exit

the result is a hidden file which I must find in the terminal with the ls -l command and requires double quotes to remove (rm ".txt").

How do I need to write my code so that the user can name the file, the computer can recall that variable name, insert that variable name into a filepath and the touch command can utilize it to create the file?

1
  • quote $file in a sentence that is already quoted basically unquotes it.
    – user986805
    Mar 8, 2020 at 16:18

1 Answer 1

3

The correct syntax is

read file

without a dollar sign (you should probably also add the -r option unless you specifically require backslashes to be parsed).

Your quoting is also off; you should definitely make sure $file is always inside double quotes, whereas static text which doesn't contain shell metacharacters can safely remain unquoted (so /path/to/"$file".txt or equivalently "/path/to/$file.txt".

A better design altogether is to read the user choice as a command-line parameter; then this script is easy to call from another script, and the user gets to use shell conveniences like command-line history and variable substitution.

1
  • Also sleep is almost never necessary or useful in interactive scripts.
    – tripleee
    Mar 7, 2020 at 10:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .