Is there a way to create a script and make it executable in less code than this?

The install command (part of GNU coreutils along with cp, mv, rm, etc.) can copy a file while also setting its ownership and permissions and creating parent directories as necessary. By default it will make the new file executable. It doesn’t understand ‘-’ but /dev/stdin can be used instead:

install /dev/stdin script.sh <<< "echo Hello World"

The above uses a ‘here string’ to provide the text on stdin, which is slightly shorter than piping it in. The arguments to echo don’t need quoting unless they contain characters with special meaning.


You can leave out the whole touch command and there’s no need to use sudo. To shorten the command line further you can use bash History Expansion to save the filename the second time, and omit unnecessary spaces:

echo "echo 'Hello World'" >script.sh&&chmod +x !#:3

History Expansion replaces !#:3 with the fourth word from the current command line, which in your case is the filename script.sh. Of course this needs to be adapted in case you modify the first command, e.g.:

>script.sh echo "echo 'Hello World'"&&chmod +x !#:1

Note that a valid script needs a shebang:

>script.sh echo -e "#!/bin/bash\necho 'Hello World'"&&chmod +x !#:1

If you need this chain of commands more often I recommend defining a function, this way you’d just need to type the function name. A similarly adaptable – though longer – way is the use of a variable holding the filename:

f=script.sh;>$f echo "echo 'Hello World'"&&chmod +x $f

If your filename contains special characters don’t forget to quote them properly.


I prefer to use cat for tasks like this:

cat > script.sh && chmod +x script.sh
#!/bin/sh
echo 'Hello World'Enter
Ctrl+D

You could also leave out the whole chmod and use umask instead before the echo. Should save you a few bytes. Shebang is optional as long as you use commands that are understood by every shell (bourne and C mainly).