Can I create a new script and chmod it in one command?
Why yes there is! Let me introduce you to the install
command. install
is a GNU-standard application that lets you copy files around and specify certain things at the same time. The short syntax is install SOURCE DESTINATION
.
However, "certain things" are important. You can specify the file mode with -m xxx
(755 for writeable by owner and executable by anyone). And bash has a couple of tricks for redirecting new files and here-doc for accepting long-form data. Here's a quick example:
install -b -m 755 /dev/stdin ~/testbin << EOF
#!/bin/sh
echo "Success!"
EOF
Now you can run ~/testbin
and it should echo out.
You can combine this with sudo
for root-owned files or if you want to write as somebody else, you can sudo and use install
's -o
owner flag.
The -b
flag just creates a backup if you run the command a second time. This is helpful if you're doing potentially destructive tasks.