简体   繁体   中英

Use of “bash” or “zsh” depending on OS and installation

I have a small function which executes a command line tool like 7za. I don't know where this tool is installed by the user, so I use this function:

func execute(commandName: String, arguments: [String]) -> String? {
        guard var bashCommand = execute(command: "/bin/bash" , arguments: ["-l", "-c", "which \(commandName)"]) else { return "\(commandName) not found" }   // find path of command itself, e.g. "/usr/local/bin/7za"
        bashCommand = bashCommand.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)   // remove newline character at the end
        if bashCommand == "" { return nil }  // command not even found! => nil
        return execute(command: bashCommand, arguments: arguments)   // now we have: /usr/local/bin/7za e -pPW -o/Users/Shared/File.JPG.7z
    }

On OSX 10.15 there is a new shell zsh. I can switch my command from bash to zsh, but my program should run on any system. How can I find out which command to use? I don't want to scan the entire harddisk to simply run an installed command line tool lile "7za". Any idea?

How can I find out which (shell) command to use?

Ideas:

  1. Use System.getenv("SHELL") to find out the shell that the user is using, and use that.

  2. Use /bin/sh . It should be a link to a POSIX compatible shell; either bash or ksh ... or possibly something else.

  3. Run ls -l /bin/ and parse the output looking for commands that match *sh .

  4. Read the /etc/shells file.

(See How can I check the available shells in Mac OSX? )

Apple have not (yet) said that bash is going away. At this stage all they have changed is what the default shell is.


But I'm not convinced it is necessary to do this in the first place:

  • You don't need to use a shell to run which . It should be available as an ordinary (not shell built-in) command. (It is on Linux...)

  • You should not need to use which 7za . What that does is to find the 7za command using the PATH variable. But that exactly the same command that will be found and executed if you simply run 7za .

  • If the user installs 7za and puts it in a strange place that is not on the PATH, they are being perverse. They need to update their PATH setting, or put the command in a more conventional place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM