Blueberry
Blueberry

Reputation: 237

Redirecting output to file shell script

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

Upvotes: 1

Views: 109

Answers (2)

clt60
clt60

Reputation: 63892

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"

Upvotes: 2

SaintHax
SaintHax

Reputation: 1943

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

Upvotes: 0

Related Questions