recentpopularlog in

kme : bash   441

« earlier  
Shell Tricks: .inputrc binding fun - BrettTerpstra.com
In Bash, there are some great but lesser-known default bindings. You may know that Option-. will insert the last argument of the previous command (e.g. running ls ~/Desktop and then typing cd and pressing Option-. will turn it into cd ~/Desktop), but did you know you can actually yank the argument at any index from the last command (without using history or ! operators)?

Just press Option-[#], where # is the position of the argument you want, then type Option-. to insert it in the current command.
inputrc  bash  dotfile  configfile 
3 days ago by kme
linux - Bash completion for path in argument (with equals sign present) - Stack Overflow
Check out the definition of COMP_WORDBREAKS in your environment to see why '--arg=<TAB>' (maybe) isn't working.
bash  programmablecompletion  tabcompletion  completion  maybesolution  workaround 
5 days ago by kme
Programmable Completion (Bash Reference Manual)
Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the Readline completion code as the list of possible completions.


See
bash  completion  tabcompletion  programmablecompletion  shellscripting  solution 
5 days ago by kme
An introduction to bash completion: part 2
I created a script and I use bash_completion, but I cannot figure out how to allow the completion of "--name=value1 --name=value2" (the "=" sign in the middle stop any other completion, and I tried to play with suffixes/prefixes without any success :s


This works:

<code class="language-bash">case "$cur" in
-t*)
cur=${cur/-t}
COMPREPLY=( $(compgen -W "${_tables[*]}" -P "-t" \
-- "$cur" ) )
return 0
;;
--table=*)
cur=${cur/--table=}
COMPREPLY=( $(compgen -W "${_tables[*]}" -P "--table=" \
-- "$cur" ) )
return
;;
*)
COMPREPLY=( $(compgen -W "${_opts[*]}" -- "$cur") )
return
;;
esac</code>
bash  programmablecompletion  tabcompletion  shellscripting  fuckina  solution 
5 days ago by kme
compgen: An Awesome Command To List All Linux Commands - nixCraft
<code class="language-bash">########################################
# Task: show all the bash built-ins
########################################
compgen -b
########################################
# Task: show all the bash keywords
########################################
compgen -k
########################################
# Task: show all the bash functions
########################################
compgen -A function</code>
bash  programmablecompletion  completion  tabcompletion  compgen  reference  newbie 
5 days ago by kme
bash - Wildcard expansion (globbing) in a string composed of quoted and unquoted parts - Stack Overflow
I had a variable that I was doing a regex comparison on within a Bash '[[ ]]' conditional that could /sometimes/ have the value of '*'; quoting didn't seem to help, but 'set -f' did.
bash  shellscripting  globbing  fileglobs  globs  workaround  solution 
6 days ago by kme
Bash causes high CPU - Apple Community
My 'bash -l' that was consistently using ~30% CPU and running the fan up was a sub-process of MacVim, which made me worry about an exploit of the modeline bug. But I was running an up-to-date version of MacVim, so it was a persistent problem, since before that CVE was released. Dunno.

It didn't have any interesting files or ports open, and just seemed to be recursing endlessly, so I just killed it... and all is well again?
mac  osx  macos  macvim  bash  highcpu  fanspeed  troubleshooting 
15 days ago by kme
stdout - How to make output of any shell command unbuffered? - Stack Overflow


Try stdbuf, included in GNU coreutils and thus virtually any Linux distro. This sets the buffer length for input, output and error to zero:
<code class="language-bash">stdbuf -i0 -o0 -e0 command</code>


This totally works for something like this:
<code class="language-bash">stdbuf -i0 -o0 -e0 find . -name 'core*' -printf '%f\t%s\n' | head</code>
bash  shellscripting  pipes  unix  buffering  solution 
5 weeks ago by kme
How (and Why) to Log Your Entire Bash History
Interesting technique, but as mentioned in the comments, you can use Bash's built-in features to do basically the same thing.

Curiously, this was the same basic approach as in the "eternal history" article at https://debian-administration.org/article/543/Bash_eternal_history.
interesting  bash  history  histfile  promptcommand  dotfile 
6 weeks ago by kme
Preserve bash history in multiple terminal windows - Unix & Linux Stack Exchange
True dat:
@Oli wrote, "I can't think of an intelligent way to do it where existing terminals only see their own history but new ones see a chronologically accurate list of commands." How about (untried): export PROMPT_COMMAND="history -a; $PROMPT_COMMAND". Existing shells will add each command to the history file for new shells to see, but only show their own histories.


Many solutions proposed, all with caveats, but this is what I decided on:

<code class="language-bash">
HISTCONTROL=ignoredups:erasedups # no duplicate entries
HISTSIZE=100000 # big big history
HISTFILESIZE=100000 # big big history
shopt -s histappend # append to history, don't overwrite

# append current history list to the history file after each command finishes
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND; }history -a"</code>

This appends lines to the history file after each command, which makes them available in other sessions, but up arrow will still reverse through the history only for the current session, which is probably less confusing.

You can bring in commands from other sessions (which have been written to the history file) with 'history -n'. Depending on the setting of 'HISTCONTROL', these might end up getting written out to the history file again, though. ¯\_(ツ)_/¯
bash  history  histfile  historyexpansion  frustration  configfile  forthecomments  solution 
6 weeks ago by kme
Bash eternal history
Many times I've found myself using Ctrl-R in Bash to get a old command four times the terminal width, just to find out that too many days have passed and it's no longer in the .bash_history file. Here are two lines that will keep track of every command line you type at the bash prompt and use no external processes at all, just plain bash.

My first approach to this problem was increasing the maximum number of lines in the history to a very large quantity. But no matter how large it was, there was always a moment when I needed a long command I typed many months ago and it had already left the history. The current solution came to my mind when I learned about the PROMPT_COMMAND variable, a command that bash executes before showing each prompt. Here are the two lines:
<code class="language-bash">export HISTTIMEFORMAT="%s "
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \
"$(history 1)" >> ~/.bash_eternal_history'</code>
bash  history  histfile  configfile  maybesolution 
6 weeks ago by kme
7 Tips - Tuning Command Line History in Bash - ShellHacks
There's nothing here that isn't in the manual, but it's a concise reference that's all in one place. Every 'shopt' and 'HISTCONTROL' option listed here seems to be supported in Bash 4.1 and above (this means CentOS 6).

The 'PROMPT_COMMAND' example, though, would clobber an existing PROMPT_COMMAND, so do it like this instead:
<code class="language-bash">PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND; }history -a"</code>
bash  history  histfile  configfile  dotfile  essential  movein  reference 
6 weeks ago by kme
Bash test: get the directory of a script
Dude made the mistake of assuming the whole world was Linux.
whereami  bash  shellscripting  tipsandtricks  tests  interesting 
7 weeks ago by kme
Get the source directory of a Bash script from within the script itself - Stack Overflow
Lots of conflicting opinions here, but here are two solid options:
<code class="language-bash">
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )
DIR=$( dirname "$(readlink -f "$0")" )
</code>
bash  shellscripting  newbie  whereami  tipsandtricks 
7 weeks ago by kme
linux - Bash arrays and negative subscripts, yes or no? - Stack Overflow
This is *way* easier than stuff I was trying to do before. The reason this doesn't show up in the help for "Arrays" in the bash manual is because it's a type of "Shell Parameter Expansion" that just happens to behave the way it does when the subscripted thing is an array.
If you just want the last element
<code class="language-bash">$ echo ${muh[*]: -1}
2</code>

If you want next to last element
<code class="language-bash">$ echo ${muh[*]: -2:1}
bleh</code>
bash  shellscripting  arrays  subscripting  syntax  fuckina  solution 
7 weeks ago by kme
linux - bashdb startup error: bashdb/lib/setshow.sh: line 91: /dev/pts/2: Permission denied - Stack Overflow - https://stackoverflow.com/
Got this error message in a CentOS 7 Docker image, added user to the 'tty' group with 'vigr', then also had to 'chmod g+r' /dev/pts/0.
bash  shellscripting  bashdb  errormessage  maybesolution 
8 weeks ago by kme
bash - unshift args after calling shift 1 - Unix & Linux Stack Exchange
You never need to use shift 1 in the first place. Just use the positional arguments and slice around their indices to pass the arguments.
<code class="language-bash">first_arg="$1"</code>

Once you do this, the rest of the arguments can be accessed as "${@:2}". The notation is a way to represent from positional argument 2 to till the end of the list.
bash  shellscripting  positionalarguments  parameters  solution 
9 weeks ago by kme
Force flushing of output to a file while bash script is still running - Stack Overflow
I found a solution to this here. Using the OP's example you basically run
<code class="language-bash">stdbuf -oL /homedir/MyScript &> some_log.log</code>

and then the buffer gets flushed after each line of output. I often combine this with nohup to run long jobs on a remote machine.
<code class="language-bash">stdbuf -oL nohup /homedir/MyScript &> some_log.log</code>

This way your process doesn't get cancelled when you log out.
bash  shellscripting  buffering  annoyance  workaround  solution 
10 weeks ago by kme
Arithmetic expressions [Bash Hackers Wiki]
Should note that return value is always decimal, and that you can use 'printf' to format the result in another base, e.g.,
<code class="language-bash">printf "%o\n" $(( 0777 & 0066 ))
# result: 66</code>
bash  expansion  arithmeticexpansion  math  needshelp  shellscripting 
10 weeks ago by kme
bash - REOPEN: Perform arithmetic expansion inside parameter expansion? - Unix & Linux Stack Exchange
Again with the 'set' trick for testing script arguments interactively:
<code class="language-bash">set 6 7; echo $(($1*$2))</code>
bash  parameterexpansion  arithmeticexpansion  shellscripting  parameters  positionalarguments  idiom  tipsandtricks 
10 weeks ago by kme
linux - bash + arithmetic calculation with bash - Unix & Linux Stack Exchange
Since arithmetic expansion only does integer division, the proposed answer uses AWK, passing in values as variables, with '/dev/null' as the input file, and the math in a 'BEGIN' block.
bash  awk  shellscripting  floatingpoint  math  tipsandtricks  solution 
10 weeks ago by kme
Builtin Bash any base to decimal conversion – Phoxis
Bash has an interesting builtin feature to convert from any base to decimal, which is a part of bash's arithmetic evaluation features. In this post i will quickly introduce you with this feature. Arithmetic Expansion To allow arithmetic evaluation of an expression and substitution of the result bash has the following construct. For example The…
bash  shellscripting  math  calculator  numericconversion  base64  base8  base10  tipsandricks 
10 weeks ago by kme
GitHub - skywind3000/z.lua: A new cd command that helps you navigate faster by learning your habits
Via: https://www.linuxuprising.com/2019/02/zlua-faster-way-of-changing-directories.html
A new cd command that helps you navigate faster by learning your habits :zap: - skywind3000/z.lua
Paste this script in your .bashrc / .zshrc:
<code class="language-bash">function j() {
if [[ "$argv[1]" == "-"* ]]; then
z "$@"
else
cd "$@" 2> /dev/null || z "$@"
fi
}</code>

When you are using j xxx it will first try cd xxx and then z xxx if cd failed.
bash  shell  cli  lua  producitivity  terminal  frecency  alternativeto  fasd  autojump 
10 weeks ago by kme
Abundant Scripting Is Good | UNIX Scripting Tips and Ideas - Kimball Hawkins
I doubt there is any System Administrator out there who doesn't realize that scripting is good, but I've found there are few who actually use scripting as I feel it should be used -- as a way to programatically improve, simplify and automate many of the complex and tedious tasks of system monitoring and maintenance.…

My first rule is, if I have to do any task more than once, I’ll script it. This applies especially if errors in the command can have serious consequences.

My second rule is, if I’m going to script it, I’m going to make it robust enough to be useful in all applicable situations.

My third rule is I never hard-code specific information in a script if I can help it.

Fourth is: If a script can figure something out, don’t require the user to enter it, or choose it or find it.

Fifth is: Document it!
sysadmin  shellscripting  unix  linux  bash 
11 weeks ago by kme
Bash scripting cheatsheet
Has links to the Bash Hackers wiki, which are helpful.

Has a really good reference for array / associative array syntax, too!
bash  shellscripting  cli  unix  linux  cheatsheet  fuckina 
11 weeks ago by kme
bash - LINES and COLUMNS environmental variables lost in a script - Stack Overflow
Solution:
<code class="language-bash">lines=$(tput lines)
columns=$(tput cols)</code>

More context:
Often, on modern systems, the $COLUMNS and $LINES variables are not environment variables. The shell sets these values dynamically after each command and we usually cannot access them from non-interactive scripts. Some programs respect these values if we export them, but this behavior isn't standardized or universally supported.

Instead, the stty and tput utilities provide portable means to determine the terminal size from a script (the commands described below are currently undergoing standardization for POSIX)
bash  shellscripting  posix  tput  terminal  solution 
may 2019 by kme
Bash Reference Manual | https://www.gnu.org/
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
bash  shell  shellscripting  ansicquoting  quoting  dammitbrain  reference 
may 2019 by kme
A ~/.inputrc for Humans - Top Bug Net | https://www.topbug.net/
<code class="language-inputrc">
$include /etc/inputrc
"\C-p":history-search-backward
"\C-n":history-search-forward

set colored-stats On
set completion-ignore-case On
set completion-prefix-display-length 3
set mark-symlinked-directories On
set show-all-if-ambiguous On
set show-all-if-unmodified On
set visible-stats On
</code>

I would add these, too:
<code class="language-inputrc">
$if mode=vi
set keymap vi-command
# these are for vi-command mode
"\e[A": history-search-backward
"\e[B": history-search-forward

set keymap vi-insert
# these are for vi-insert mode
"\e[A": history-search-backward
"\e[B": history-search-forward

# source: https://brettterpstra.com/2015/07/09/shell-tricks-inputrc-binding-fun/
"\e[1;5C": forward-word
"\e[1;5D": backward-word
$endif
</code>
bash  commandline  editing  configfile  dotfile  movein  essential  newbie  inputrc  readline 
april 2019 by kme
Intrepid command line directory traversal - BrettTerpstra.com | https://brettterpstra.com/
I use Terminal (well, iTerm 2) for file management on my Mac more often than I use Finder. Typing out long path names is often more tedious than drilling through Finder folders, though. I have enough
unix  shell  bash  commandline  filesystemnavigation  tipsandtricks 
april 2019 by kme
Is there a way of reading the last element of an array with bash? - Unix & Linux Stack Exchange | https://unix.stackexchange.com/
Bash array assignment, reference, unsetting with negative index were only added in bash 4.3. With older version of bash, you can use expression in index, like
<code class="language-bash">
array[${#array[@]-1}]
</code>

Another way, also work with older version of bash (bash 3.0 or better):
<code class="language-bash">
$ a=([a] [b] [c] [d] [e])
$ printf %s\\n "${a[@]:(-1)}"
[e]
</code>/blockquote>
bash  arrays  subscript  slice  solution  oldbash  bash4 
april 2019 by kme
How to setup trap in bash functions? - Unix & Linux Stack Exchange
Accepted answer suggests making function asynchronous (put it in the background?) and using 'wait'. I do not understand this.
Protip: Send the foreground process a QUIT with Ctrl-\ when Ctrl-C, -Z, -D aren't working.

Clear traps at the end of execution with trap - list of signals here

Fun on a non-production system: Try setting a trap for all sensible signals (e.g., not KILL). kill -l (not that's a lower-case L not a number 1 or pipe |)
bash  shellscripting  signals  processmanagement  tipsandtricks  reference 
april 2019 by kme
interrupt handling - How to trap ERR when using 'set -e' in Bash - Stack Overflow | https://stackoverflow.com/
This wasn't my original question, which was why was "trap 'cleanup; exit 1' 1 2 15" not working, but the answer is you have to trap 'ERR', too.
If you want to combine set -e (same as: set -o errexit) with an ERR trap, also use set -o errtrace (same as: set -E).

In short: use set -eE in lieu of just set -e:
<code class="language-bash">
#!/bin/bash

set -eE # same as: `set -o errexit -o errtrace`
trap "echo BOO!" ERR

function func(){
ls /root/
}

func
</code>
bash  signals  trap  shellscripting  solution  reference 
april 2019 by kme
linux - How to use sed to remove the last n lines of a file - Stack Overflow | https://stackoverflow.com/
Yeah, it's possible in 'sed', but ugly.

<code class="language-bash">head -n -2 myfile.txt</code>
bash  linux  sed  shellscripting  textprocessing  solution 
march 2019 by kme
linux - Why redirect stdin inside a while read loop in bash? - Stack Overflow | https://stackoverflow.com/
The clear intent here is to prevent do_something from reading from the sample.text stream, by ensuring that its stdin is coming from elsewhere. If you're not seeing differences in behavior with or without the redirection, that's because do_something isn't actually reading from stdin in your tests.

[...]

By the way, I would write this more as follows:
<code class="language-bash">exec 3</dev/tty || exec 3<&0 ## make FD 3 point to the TTY or stdin (as fallback)

while read -a args; do ## |- loop over lines read from FD 0
do_something "${args[@]}" <&3 ## |- run do_something with its stdin copied from FD 3
done <sample.text ## \-> ...while the loop is run with sample.txt on FD 0

exec 3<&- ## close FD 3 when done.</code>

It's a little more verbose, needing to explicitly close FD 3, but it means that our code is no longer broken if we're run with stdout attached to the write-only side of a FIFO (or any other write-only interface) rather than directly to a TTY.
bash  shellscripting  stdin  filedescriptors  epiphany  tipsandtricks  solution 
march 2019 by kme
posix - How to check if stdin is from the terminal or a pipe in a shell script? - Stack Overflow | https://stackoverflow.com/
<code class="language-bash">#!/bin/sh
if [ -t 0 ]; then
echo running interactivelly
else
while read -r line ; do
echo $line
done
fi</code>
bash  shellscripting  stdin  dammitbrain  solution 
march 2019 by kme
linux - Remove a certain line from Bash history file - Super User | https://superuser.com/
You can achieve removal from the history file using the commandline in two steps:

Typing history -d <line_number> deletes a specified line from the history in memory.
Typing history -w writes the current in-memory history to the ~/.bash_history file.

The two steps together remove the line permanently from the in-memory history and from the .bash_history file as well.
bash  history  security  cya  oops  solution  fuckina 
march 2019 by kme
How to get $HOME directory of different user in bash script? - Stack Overflow | https://stackoverflow.com/
<code class="language-bash">eval echo "~$different_user" # prints $different_user's home dir.</code>
sysadmin  homedirectory  bash  tipsandtricks  solution 
march 2019 by kme
How can I join elements of an array in Bash? - Stack Overflow | https://stackoverflow.com/
Other, more complicated solutions (multiple-letter separators) require 'printf' and have their own problems.

<code class="language-bash">
IFS=, eval 'joined="${foo[*]}"'
</code>
bash  arrays  shellscripting  syntax  solution  likepython 
march 2019 by kme
linux - Why does BASH process substitution not work with some commands? - Unix & Linux Stack Exchange | https://unix.stackexchange.com/
The error message would come about when you tried to do something like
<code class="language-bash">
gcc <(echo "#include <X11/Xatom.h>
> int main() { return 0; }") -lX11
# result:
# /dev/fd/63: file not recognized: Illegal seek
# collect2: error: ld returned 1 exit status
</code>
gcc wants to be able to perform random access on its input files to detect what language they are written in. If you instead give gcc a hint about the input file's language, it's happy to stream the file:
<code class="language-bash">
gcc -x c <(echo 'int main(){return 0;}')
</code>/blockquote>
devel  build  toolchain  makefile  gcc  bash  processsubstitution  solution 
february 2019 by kme
man command not found on git bash · Issue #249 · swcarpentry/shell-novice | https://github.com/
man doesn't seem to be installed on git bash - learners get a "man: command not found" error when they try to use it.
softwarecarpentry  git  gitforwindows  bash  annoyance  packagemanagement  workaround  solution 
february 2019 by kme
The #! magic, details about the shebang/hash-bang mechanism | https://www.in-ulm.de/
what's special about #!

#! was a great hack to make scripts look and feel like real executable binaries.

But, as a little summary, what's special about #!? (list mostly courtesy of David Korn)

- the interpretername must not contain blanks
- the length of the #! is much smaller than the maximum path length
- $PATH is not searched for the interpreter
- (apart from an absolute path, the #! line also accepts a relative path,
- and #!interpreter is equivalent to #!./interpreter,
- however, it's not of any practical use)
- the interpreter usually must no be a #! script again
- the handling of arguments in the #! line itself is varying
- the setuid mechanism may or may not be available for the script
- there's no way to express #!$SHELL

And why shebang? In music, '#' means sharp. So just shorten #! to sharp-bang. Or it might be derived from "shell bang". All this probably under the influence of the american slang idiom "the whole shebang" (everything, the works, everything involved in what is under consideration). See also the wiktionary, jargon dictionary or Merriam-Websters. Sometimes it's also called hash-bang, pound-bang, sha-bang/shabang, hash-exclam, or hash-pling (british, isn't it?).

According to Dennis M. Ritchie (email answer to Alex North-Keys) it seems it had no name originally.
And Doug McIllroy mentioned (TUHS mailing list), that the slang for # at Bell Labs most probably was "sharp" at the time.
bourne  bash  posix  shell  shebang  unix  linux  shellscripting  history  butwhy  explained 
february 2019 by kme
swcarpentry/windows-installer: Software Carpentry installer for Windows. | https://github.com/
Software Carpentry installer for Windows. Contribute to swcarpentry/windows-installer development by creating an account on GitHub.
workshop  windows  unix  msysgit  commandline  bash  installation  installer  script  python 
february 2019 by kme
Man pages for Git Bash on Windows 7 - Super User | https://superuser.com/
Yeah, if you want man pages by default, it's actually more prudent to do a default install of Cygwin.

You /could/ install Python, then 'pip install tldr', but that's not a good solution for a workshop.
windows  bash  git  shell  unix  workshop  howto 
february 2019 by kme
The Unix Shell: Instructor Notes | https://swcarpentry.github.io/
Many people have questioned whether we should still teach the shell. After all, anyone who wants to rename several thousand data files can easily do so interactively in the Python interpreter, and anyone who’s doing serious data analysis is probably going to do most of their work inside the IPython Notebook or R Studio. So why teach the shell?

The first answer is, “Because so much else depends on it.” Installing software, configuring your default editor, and controlling remote machines frequently assume a basic familiarity with the shell, and with related ideas like standard input and output. Many tools also use its terminology (for example, the %ls and %cd magic commands in IPython).

The second answer is, “Because it’s an easy way to introduce some fundamental ideas about how to use computers.” As we teach people how to use the Unix shell, we teach them that they should get the computer to repeat things (via tab completion, ! followed by a command number, and for loops) rather than repeating things themselves. We also teach them to take things they’ve discovered they do frequently and save them for later re-use (via shell scripts), to give things sensible names, and to write a little bit of documentation (like comment at the top of shell scripts) to make their future selves’ lives better.

The third answer is, “Because it enables use of many domain-specific tools and compute resources researchers cannot access otherwise.” Familiarity with the shell is very useful for remote accessing machines, using high-performance computing infrastructure, and running new specialist tools in many disciplines. We do not teach HPC or domain-specific skills here but lay the groundwork for further development of these skills. In particular, understanding the syntax of commands, flags, and help systems is useful for domain specific tools and understanding the file system (and how to navigate it) is useful for remote access.

Finally, and perhaps most importantly, teaching people the shell lets us teach them to think about programming in terms of function composition. In the case of the shell, this takes the form of pipelines rather than nested function calls, but the core idea of “small pieces, loosely joined” is the same.

Installing Bash and a reasonable set of Unix commands on Windows always involves some fiddling and frustration. Please see the latest set of installation guidelines for advice, and try it out yourself before teaching a class.

Tab completion sounds like a small thing: it isn’t. Re-running old commands using !123 or !wc isn’t a small thing either, and neither are wildcard expansion and for loops. Each one is an opportunity to repeat one of the big ideas of Software Carpentry: if the computer can repeat it, some programmer somewhere will almost certainly have built some way for the computer to repeat it.

Building up a pipeline with four or five stages, then putting it in a shell script for re-use and calling that script inside a for loop, is a great opportunity to show how “seven plus or minus two” connects to programming. Once we have figured out how to do something moderately complicated, we make it re-usable and give it a name so that it only takes up one slot in working memory rather than several. It is also a good opportunity to talk about exploratory programming: rather than designing a program up front, we can do a few useful things and then retroactively decide which are worth encapsulating for future re-use.
shellscripting  unix  linux  shell  bash  butwhy  programming  sevenplusorminustwo  teaching  workshop  reference  advice  bestpractices 
february 2019 by kme
bash - How can I prevent unsupported 'shopt' options from causing errors in my .bashrc? - Unix & Linux Stack Exchange | https://unix.stackexchange.com/
But if you really dislike redirecting the error away, you can use the completion mechanism to perform introspection. This assumes that you don't have antiquated machines with bash ≤ 2.03 that didn't have programmable completion.
<code class="language-bash">
shopt_exists () {
compgen -A shopt -X \!"$1" "$1" >/dev/null
}
if shopt_exists direxpand; then
shopt -s direxpand
fi
</code>

This method avoids forking, which is slow on some environments such as Cygwin. So does the straightforward 2>/dev/null, I don't think you can beat that on performance.
bash  configfile  shellscripting  shopt  programmablecompletion  tabcompletion  schooling  solution 
february 2019 by kme
Bash Builtins (Bash Reference Manual) | https://www.gnu.org/
Here's how you pretty-print arrays in Bash:
The -p option will display the attributes and values of each name. When -p is used with name arguments, additional options, other than -f and -F, are ignored.
bash  shellscripting  prettyprinting  arrays  solution 
february 2019 by kme
bash - How to expand filenames with Tab, even when a shell variable is used in the path? - Unix & Linux Stack Exchange | https://unix.stackexchange.com/
The solution is 'shopt -s direxpand' in Bash 4.2 or later. This is (supposedly) the default on 4.1 and earlier. I learned that "Ctrl+Alt+E" does something cool when you 'set -o emacs', though:
For example, typing less $lh/acc then hitting Tab will expand to: less \$lh/access_log.

Of course, what I would like instead is less $lh/access_log or even less /var/log/httpd/access_log. (weirdly, with the cd command the autocomplete doesn't work at all in that case, this question already talks about it)

I know that there is an alternative by using shell-expand-line (default key: Ctrl+Alt+E), but it's far from perfect because it expands aliases as well, and it doesn't quote paths with special chars (spaces, ...).
bash  tabcompletion  movein  configfile  interesting 
february 2019 by kme
bash - Set and Shopt - Why Two? - Unix & Linux Stack Exchange | https://unix.stackexchange.com/
The difference is in the changed environment variable used by bash. Setting with the set command results in $SHELLOPTS. Setting with the shopt command results in $BASHOPTS.
bourne  bash  shell  configfile  configuration  history  butwhy  explained 
february 2019 by kme
linux - bash: variable name not being expanded with Tab completion - Super User | https://superuser.com/
shopt -s direxpand will make echo $HOME/<tab> expand to echo /home/matt/ in bash 4.2. In bash 4.1 it should be the default.
bash  tabcompletion  bashcompletion  commandline  shell  configfile  essential  movein  annoyance  solution  fuckina 
february 2019 by kme
Xterm Titles With Bash - David Pashley.comDavid Pashley.com | https://web.archive.org/
<code class="language-bash">
if [ "$SHELL" = '/bin/bash' ]
then
case $TERM in
rxvt|*term)
set -o functrace
trap 'echo -ne "\e]0;"; echo -n $BASH_COMMAND; echo -ne "\007"' DEBUG
export PS1="\e]0;$TERM\007$PS1"
;;
esac
fi
</code>
bash  dynamictitle  xterm  configfile  ps1  promptstring  maybesolution 
january 2019 by kme
ingydotnet/...: Dot Dot Dot | https://github.com/
Dot Dot Dot. Contribute to ingydotnet/... development by creating an account on GitHub.
dotfiles  configfiles  bash  shell 
january 2019 by kme
bats-core/bats-core: Bash Automated Testing System | https://github.com/
Bash Automated Testing System. Contribute to bats-core/bats-core development by creating an account on GitHub.
shellscripting  bash  testing  framework  unittesting  automation  devel  alternative  to  ts  bats 
january 2019 by kme
software recommendation - Any command line calculator for Ubuntu? - Ask Ubuntu | https://askubuntu.com/
Another possible solution is to add a simple function for Bash's builtin arithmetic. Put this in your .bashrc file to try:
<code class="language-bash">
=() {
echo "$(($@))"
}
</code>
math  calculator  bash  commandline  bashrc  essential 
december 2018 by kme
« earlier      
per page:    204080120160

Copy this bookmark:





to read