-2

Having the following Bash sequence that creates a file, changes file permissions (to be executable) and run the script I want to do in one line the last 2 commands:

$ touch dotfiles.sh
$ chmod +x ./dotfiles.sh
$ ./dotfiles

Solution 1

I thought a possible solution is to use the && operator. So ./dotfiles will be executed only if chmod succeeds.

But this solution is not working and bash says the file does not exists. Any idea?.

(not working solution)

Note: chmod returns 0 if success. So the && is done, but fails in the second part when ./dotfiles.sh:

$ chmod +x ./dotfiles.sh && ./dotfiles.sh
-bash: ./dotfiles.sh: No such file or directory
$

Update: Solution 1 is correct. See my answer below to full explanation.

jorge
  • 19
  • 1
  • 4
  • Does it work when you execute the commands one by one? – Roman Mar 27 '16 at 05:27
  • @Roman Yes! It works when you execute the chmod first and then the ./dotfiles. The idea is to make those in one line. Any idea? – jorge Mar 27 '16 at 05:45
  • What's the output of `touch dotfiles.sh && chmod +x ./dotfiles.sh && echo $?` ? – SLePort Mar 27 '16 at 05:50
  • 1
    You have made `dotfiles.sh` executable, but you try to run `dotfiles` — that isn't going to work. Either copy `dotfiles.sh` to `dotfiles` and make `dotfiles` executable, or run `dotfiles.sh`. – Jonathan Leffler Mar 27 '16 at 06:01
  • 1
    Note that if you fail to run `./dotfiles.sh`, then the chances are that you've got an error on the 'shebang' line (`#!/bin/sh` or similar). You can get 'file not found' errors if the file named does not exist — for example, if you have `#!bin/sh`, missing a `/`. – Jonathan Leffler Mar 27 '16 at 06:10
  • With a shebang typo, the error would have rather been `̀bash: ./dotfiles.sh: bad interpreter: No such file or directory`. – SLePort Mar 27 '16 at 06:24
  • @Kenavoz Hi! The output for that script is 0. Because everything is working. Thanks to your example, I came up with a solution to my code. I'm going to update the post ;). – jorge Mar 27 '16 at 07:29

2 Answers2

2

Update:

Solution 1 proposed was in fact working. After reading user's comments I figured out that the problem may be with the content of dotfiles.sh and not with the bash command I was asking for.

What problem I had?

In the dotfile.sh file, I included #!/usr/bin/env bash instead of #!/bin/bash. So when executing chmod +x ./dotfiles.sh && ./dotfiles.sh the "No such file or directory" problem, was referring to the ./dotfiles.sh content and not with the "command" itself (that I thought).

jorge
  • 19
  • 1
  • 4
-3

This should work.

chmod +x dotfiles.sh; [ $? -eq 0 ] && ./dotfiles.sh
Brian Mc
  • 141
  • 8