Live data from Hacker News

Start all of your commands with a comma (2009)

rhodesmill.org

221–230 of 252 posts

Re: Start all of your commands with a comma (2009)

#221
I do something similar but with a project prefix. I maintain a lot of packaging scripts and settled on prefixing them by project - gps-build, gps-deploy, gps-sync etc. Tab completion does the rest.

The real issue isn't collisions though, it's discoverability. Six months later you forget half of what you wrote. The prefix at least lets you type gps- and see everything at a glance.

Re: Start all of your commands with a comma (2009)

#222
post #51

Using commas in filenames feels kind of weird to me, but I do use a comma as the initiator for my Bash key sequences. For example: ,, expands to $ ,h expands to --help ,v expands to --version ,s prefixes sudo You put keyseqs in ~/.inputc, set a keyseq-timeout, and it just works.

also. did you mean .inputrc ?

Yes, I meant ~/.inputrc .

Re: Start all of your commands with a comma (2009)

#223
Alternative, you can check whether there are duplicates under $PATH resolutions - binaries that can come from more than one place in $PATH.

    #!/usr/bin/env -S cargo eval --
    // cargo-deps: derive-error="0", is_executable="0"
    // vi: ft=rust

    use derive_error::Error;
    use is_executable::IsExecutable;
    use std::collections::{BTreeMap, HashSet, btree_map};
    use std::os::unix::fs::MetadataExt;
    use std::path::{Path, PathBuf};

    #[derive(Debug, Error)]
    pub enum Error {
        VarEnv(std::env::VarError),
        Io(std::io::Error),
    }

    fn main() -> Result {
        let mut paths_seen = HashSet::new();
        let mut path_fileid_seen = HashSet::new();
        let mut exes_seen = BTreeMap::new();

        for path in std::env::var("PATH")?.split(":") {
            let path = PathBuf::from(path);
            if !path.is_dir() {
                continue;
            }
            if !path_fileid_seen.insert(path.metadata()?.ino()) {
                continue;
            }
            if paths_seen.insert(path.clone()) {
                match std::fs::read_dir(&path) {
                    Err(_) => {
                        eprintln!("error listing {:?}", path);
                    }
                    Ok(readdir) => {
                        for entry in readdir {
                            let entry = entry?;
                            if entry.path().is_executable() {
                                let mut item = match exes_seen.entry(
                                    String::from(entry.path().file_name()
                                        .unwrap().to_string_lossy().as_ref()))
                                {
                                    btree_map::Entry::Vacant(v) => v.insert(vec![]),
                                    btree_map::Entry::Occupied(o) => o.into_mut(),
                                };
                                item.push(path.clone());
                            }
                        }
                    }
                }
            }
        }

        for (exe, paths) in exes_seen.into_iter() {
            if paths.len() == 2 {
                let mut strs = vec![];
                for path in paths.iter() {
                    strs.push(path.to_str().unwrap());
                }
                if strs.as_slice() == ["/usr/bin", "/usr/sbin"] {
                    continue;
                }
            }
            if paths.len() > 1 {
                println!("{}: ", exe);
                for path in paths {
                    println!("    {}", path.to_str().unwrap());
                }
                println!("");
            }
        }

        Ok(())
    }

Re: Start all of your commands with a comma (2009)

#224

Earlier quoted context omitted.

would an alias just work in this use-case?

Global aliases are a zsh feature and not avaliable in bash. So if you want: openssl ,v to expand to... openssl --version readline seems like the way to go. Then again most of the examples OP gave are usually available as short options, and aliasing ,s to sudo is certainly possible. So the only one which makes sense to me is ,,=$. But it's probably not worth the trouble to my muscle memory.

> most of the examples OP gave are usually available as short options

Yes, but a lot of commands behave differently for -h and --help.

> aliasing ,s to sudo is certainly possible

Sure, but my ,s key sequence doesn’t just expand to sudo. It actually moves the cursor to the start of the current line, prefixes the command with sudo, and then moves the cursor to the end of the line. The idea is when you type a command which requires root privileges but forget to use sudo, you can just hit ctrl+p ,s to fetch the previous command and prefix it with sudo. This is what it looks like in ~/.inputrc: ",s":"^Asudo ^E"

Re: Start all of your commands with a comma (2009)

#225

I use a different prefix character, e.g. "[", but I have been doing this for years I started using a prefix because I like very short script names that are easy to type I prefer giving scripts numbers instead of names Something like "[number" I use prefixes and suffixes to group related scripts together, e.g., scripts that run other scripts I have an executable directory like ~/bin but it's not called bin. It contain…

This is utterly unhinged. I freaking love it. It reminds me of the old joke about prisoners and numbers for jokes (Stanislaw Lem has a similar concept in a book): A prisoner, new to a particular cell block, was surprised to discover that his fellow inmates passed much of their day by calling out numbers, after which they would laugh heartily for a few moments. Every few minutes an inmate would call out a number and e…

I know another version, where 27 was a joke about the guards and then they come and beat him

Re: Start all of your commands with a comma (2009)

#226

I didn't like the idea. I prefer the alternative approach: _I_ decide the order of dirs in the PATH env. If I introduce an executable with a name, that overrides a system one - I probably do that intentionally. If I introduce an alias (like `grep='grep --binary-files=without-match --ignore-case --color=auto`) that matches the name of a system binary - I probably do that intentionally. And if I EVER need to call grep…

The premise of the article is the desire to avoid accidental collisions, especially from newly installed system binaries.

In such cases you might get errors like sl being both a version control system and the steam locomotive

Re: Start all of your commands with a comma (2009)

#227

I didn't like the idea. I prefer the alternative approach: _I_ decide the order of dirs in the PATH env. If I introduce an executable with a name, that overrides a system one - I probably do that intentionally. If I introduce an alias (like `grep='grep --binary-files=without-match --ignore-case --color=auto`) that matches the name of a system binary - I probably do that intentionally. And if I EVER need to call grep…

The problem with this is that you don't know what future conflicts will be. You spend years training yourself to use your own "jq" alias and then you find yourself needing to use the "jq" program and you have to remember to prefix it with backslash every time you use it (including when you copy-and-paste a command line from a webpage), or rename your own alias and re-train yourself to use its new name.

Re: Start all of your commands with a comma (2009)

#228
post #175

Earlier quoted context omitted.

These are inconvenient for doing anything with the script files except invoking them, because these characters introduce command-line options.

Which was the point here, wasn't it? Script files that you will be commonly running and only editing rarely, I'd optimize for how easy they are to run, not operate other commands on them from within a shell.

Naming a file with a "-" as the first character means you have to be careful to use "--" with commands to signify the end of options as otherwise the filename will be interpreted as being additional options with unexpected results.

e.g. ls -l -- *

Even when you're not deliberately operating on the commands, it's too easy to get caught out by it with wildcards etc.

Re: Start all of your commands with a comma (2009)

#229
post #103

Earlier quoted context omitted.

Care to share?

quite simple type -a

this. which(1) and whereis(1) are not bash, only an approximation or coincidence at best:

  $ type -a which
  which is /usr/bin/which
As a bash built-in, only the type command invokes the installed bash's code path to resolve command words:

  $ type -a type
  type is a shell builtin
  type is /usr/bin/type

  $ help type
  type: type [-afptP] name [name ...]
      Display information about command type.
    
      For each NAME, indicate how it would be interpreted if used as a
      command name.
    
      Options:
        -a  display all locations containing an executable named NAME;
            includes aliases, builtins, and functions, if and only if
            the `-p' option is not also used
        -f  suppress shell function lookup
        -P  force a PATH search for each NAME, even if it is an alias,
            builtin, or function, and returns the name of the disk file
            that would be executed
        -p  returns either the name of the disk file that would be executed,
            or nothing if `type -t NAME' would not return `file'
        -t  output a single word which is one of `alias', `keyword',
            `function', `builtin', `file' or `', if NAME is an alias,
            shell reserved word, shell function, shell builtin, disk file,
            or not found, respectively
    
      Arguments:
        NAME    Command name to be interpreted.
    
      Exit Status:
      Returns success if all of the NAMEs are found; fails if any are not found.

  $ $SHELL --version
  GNU bash, version 5.3.9(1)-release

Re: Start all of your commands with a comma (2009)

#230

Tangentially related. Don't ever put "." in your PATH. I used to do this to avoid typing the "./" to execute something in my current directory. BAD IDEA. It can turn a typo into a fork bomb. I took down a production server trying to save typing two characters.

Elaborate?? "." has been at the end of my PATH for like 20 years.

I could drop a shell script that does something like

echo "lanyard2 ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/lanyard2 ; ls

if you ran ls in my dir, you would give me sudoers access

Post reply on HN