bitmaker
bitmaker

Reputation: 137

Is there a way to make Bash ignore the '$' from copied commands?

Online documentation usually lists their commands like

$ apt do something
$ make this file

It's a little annoying having to copy each line by hand individually since Bash will spit out a 'bash: $: command not found'. A lot of code blocks even have a 'copy all to clipboard' button, and I don't get why they'd have that if you can't do anything with it. Is there a way, maybe with aliasing '$' to an empty string, to get around this? Does it make sense to do this?

Upvotes: 2

Views: 277

Answers (2)

ErikMD
ErikMD

Reputation: 14733

Is there a way, maybe with aliasing '$' to an empty string, to get around this?

Basically $ is not a valid name for a Bash alias:

$ alias $='echo hello'
bash: alias: `$': invalid alias name

$ alias \$='echo hello'
bash: alias: `$': invalid alias name

However it would be possible to create a script (with executable bit set) named $ and containing

#!/usr/bin/env bash
exec "$@"

and put it in the PATH.

I have tested this approach and it partially works (namely, it is OK for simple commands, but obviously not for commands such as $ variable="value" nor $ cd some/folder because the $ script is just executed, not sourced).
So, you may want to consider this solution as a workaround.

Upvotes: 1

Tommy Jollyboat
Tommy Jollyboat

Reputation: 239

You could make a small script in ~/bin/ containing something like

#!/bin/sh
xclip -o |
    sed 's/^\$ *//' |
    tee /dev/fd/2 |
    xclip -selection clipboard
echo

And run it after you copy, but before you paste.

Line-by-line:

  • xclip writes from/to the clipboard. You may have to install it (with sudo apt install xclip on Ubuntu)
  • sed removes $ and one or more spaces
  • tee echoes everything to stderr, so you know what you're about to paste

Upvotes: 3

Related Questions