4

I wrote a very simple program to test outputting data to a file name variable.

#!/bin/sh
file="~/output"
echo "test" > $file

When I run this script, I got the following error

"./script.sh: line 3: ~/output: No such file or directory"

So how should I revise my code to get it work? Or it's not supported in shell script?

2 Answers 2

5

The quotes around the "~/output" are causing you grief.

e.g

#!/bin/sh
file=~/output
echo "test" > $file

works ok.

To see what's going on, try

$ file="~/output"
$ echo $file

vs

$ file=~/output
$ echo $file

and bear in mind that ~ is a shell expansion for the home directory.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the $HOME environment variable instead in a script:

#!/bin/sh
file="$HOME/output"
echo "test" > $file

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.