1

I'm trying to make a script that will take an input from a user (a name and username) then direct that input to a text file named with that username. The code I have below will create the file, however doesn't direct any of the data into the file. Can anybody help me with this problem? Thanks

echo "What is your name?"
read name
echo "What is your chosen username?"
read username
cd user_records
$name >> "$username".txt
$username >> "$username".txt
1
  • 2
    Add echo... echo $name >>... Commented Apr 27, 2017 at 16:46

2 Answers 2

2

Few comments:

  • You could to use the -p parameter to read.
  • Also always use the -r unless you know why don't want it.
  • you should check the success of the cd - what if it is unsuccessful?
  • always quote your variables
#!/bin/bash
err(){ echo "$@" >&2; return 1; }

udir="./user_records"

read -r -p  'What is your name?> ' name
read -r -p  'What is your chosen username?> ' username
cd "$udir" || err "Can't cd to $udir" || exit 1
printf "%s\n%s\n" "$name" "$username" >> "$username.txt"

or maybe you don't need cd, in such case you can write

err(){ echo "$@" >&2; return 1; }

udir="./user_records"

read -r -p  'What is your name?> ' name
read -r -p  'What is your chosen username?> ' username
[[ -d "$udir" ]] || err "The $udir doesn't exists" || exit 1
printf "%s\n%s\n" "$name" "$username" >> "$udir/$username.txt"
Sign up to request clarification or add additional context in comments.

4 Comments

Cheers, I'll give that a go!
Yeah, I had a lot of other stuff, but deleted it-- it felt like over kill for what was asked. I dunno.
btw, my standard cd error checking is cd dir || { echo "error" >&2; exit 40; } Stringing two || isn't needed. Also, you can do read -rp "this is my prompt: " and save some spaces :-)
@jm666 you missed my point. I actually have a function library that has a log() and err() that also prepends the string with a date/time string. My point was that you are doing two OR commands, instead of wrapping your error message and exit in curly-braces.
0

Lohmar gave the answer, but you need to echo the variable. Your code is trying to execute $name and $username, but you need to use it as data, not a command.

echo -n "What is your name? "
read name
echo -n "What is your chosen username? "
read username
cd user_records
echo "$name" >> "$username".txt
echo "$username" >> "$username".txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.