37

I would like to write the following on one line in the terminal or if there is a shorter way to create a file and set the permissions then please do comment.

sudo touch .htaccess
sudo chmod 766 .htaccess

Much appreciated

4 Answers 4

51

Use && to conditionally run the second command if the first is successful:

$ sudo touch .htaccess && sudo chmod 766 .htaccess

2
  • 3
    I prefer this solution for two reasons: 1. && is generally better than ; so that it stops if the first command fails, 2. it's generally better to only run the specific program needed with sudo, rather than trying to combine them into a single sudo invocation and running more code with elevated privileges than necessary.
    – Chris Page
    Jun 29, 2012 at 12:14
  • What if I want to do scp [email protected]:file1 && scp [email protected]:file2 && scp [email protected]:file3 and I have set password on my SSH key, it is asking me for password all the time, is there a way to combine it??? Dec 5, 2018 at 5:48
6

Semicolons will let you fit multiple commands on a single line like this:

sudo touch .htaccess; sudo chmod 766 .htaccess

2
  • 2
    That's a good suggestion, though it's a good idea to get into the habit of using && instead of ; when running interdependent commands so that it stops if a command fails.
    – Chris Page
    Jun 29, 2012 at 12:16
  • @ChrisPage OP asked only to combine two commands, he didn't put the condition. I am saying so because it is what I was looking for e.g. If the build fails (first cmd), still reports get generate at the end (second cmd). Please correct me if I am wrong.
    – paul
    Apr 9, 2020 at 19:19
2

No, it is not.

The only thing you can make, you can combine these two commands within one sudo:

sudo sh -c 'touch .htaccess && chmod 766 .htaccess'

Another solution (witho ony one external call, but also with two commands):

sudo sh -c 'umask 011 && touch .htaccess'
2
  • 1
    Good suggestions, but I would revise these to use && instead of ;, though. Also, in general I would just use two sudo commands, because it's overkill and riskier to run an entire shell with elevated privileges, rather than just the exact programs that need to run with them (in this case, touch and chmod).
    – Chris Page
    Jun 29, 2012 at 12:12
  • Yes, you are right, it would be better Jun 29, 2012 at 12:17
0

separate the commands with semicolon. (;)

Example

echo firstname; echo lastname;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .