问题描述:

I want to save a command to a file (for example I want to save the string "cat /etc/passwd" to a file) but I can't use the echo command.

How can I create and save string to a file directly without using echo command?

网友答案:

You can redirect cat to a file, type the text, and press Control-D when you're done, like this:

cat > file.txt
some text
some more text
^D

By ^D I mean to press Control-D at the end. The line must be empty. It will not be part of the file, it is just to terminate the input.

网友答案:

Are you avoiding ECHO for security purposes (e.g. you're using a shared terminal and you don't want to leave trace in the shell history of what you've written inside your files) or you're just curious for an alternative method?


Simple alternative to echo:

As someone said, redirecting cat is probably the simpler way to go. I'd suggest you to manually type your end-of-file, like this:

cat <<EOF > outputfile

> type here
> your 
> text
> and finish it with
> EOF

Here's the string you're asking for, as an example:

 cat <<EOF > myscript.sh
    cat /etc/passwd
    EOF

You probably don't want everyone to know you've peeked into that file, but if that's your purpose please notice that wrapping it inside an executable file won't make it more private, as that lines will be logged anyway...


Security - Avoiding history logs etc..

In modern shell, just try adding a space at the beginning of every command and use freely whatever you want.

BTW, my best hint is to avoid using that terminal at all, if you can. If you got two shells (another machine or even just another secure user in the same machine), I'd recommend you using netcat. See here: http://www.thegeekstuff.com/2012/04/nc-command-examples/?utm_source=feedburner

网友答案:
 { { command ls $(dirname $(which cat)) | 
    grep ^ca't$'; ls /etc/passwd; } | 
    tr \\n ' '; printf '\n'; }  > output-file

But it's probably a lot simpler to just do : printf 'cat /etc/passwd\n'

To be clear, this is a tongue-in-cheek solution. The initial command is an extraordinarily convoluted way to get what you want, and this is intended to be a humorous answer. Perhaps instructive to understand.

网友答案:

I am not sure I understood you correctly but

    cat /etc/passwd > target.file

use the > operator to write it to file without echoing

网友答案:

If you need to use it, inside a program :

cat <<EOF >file.txt
some text
some more text
EOF
网友答案:

I would imagine that you are probably trying to print the content of a string to a file, hence you mentioned echo.

You are avoiding this:

echo "cat /etc/passwd" > target.file

You can use a here string combined with cat.

cat > target.file <<< "cat /etc/passwd"

Now the file target.file will contain a string cat /etc/passwd.

$ cat target.file
cat /etc/passwd
$
网友答案:

To create string: var1=your command to save a file or variable in a file without echo use: cat $FILE/VAR1 > /new/file/path

相关阅读:
Top