date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,478,106,400,000
I came across a bash_profile file that makes use of the export -f statement in the following manner: # Run xelatex and BibTeX function xelatex_bibtex { xelatex -shell-escape "${1}.tex" && bibtex "${1}" && xelatex -shell-escape "${1}.tex" && xelatex -shell-escape "${1}.tex" } export -f xelat...
Its role is exactly analogous to that in the case of variables - i.e. to export the definition to inherited environments. So $ foo() { echo bar; } $ foo bar Start a child shell $ bash Now: $ foo Command 'foo' not found, did you mean: command 'roo' from snap roo (2.0.3) command 'fio' from deb fio command 'fgo...
Role of export -f statement when creating functions in bash_profile
1,478,106,400,000
In my script, I found some operations on an array are reusable. So I am considering to refactor the reusable code into a function or a script. However how can I write a function or script so that I can provide an array as a positional parameter to a function or script? or achieve something similar? Thanks.
Using a name reference in a recent (>=4.3) version of bash: foo () { local param1=$1 local -n arr=$2 printf 'array: %s\n' "${arr[@]}" } myarray=( some items go here ) foo something myarray The name of the array variable is passed as the second parameter to the function. The function declares a name ref...
how can I can provide an array as a positional parameter to a function or script?
1,478,106,400,000
declare -f Shows function definition in both bash & zsh. $ declare -f VCS_INFO_adjust () { # undefined builtin autoload -XUz } VCS_INFO_bydir_detect () { # undefined builtin autoload -XUz } VCS_INFO_check_com () { setopt localoptions NO_shwordsplit case $1 in (/*) [[ -x $1 ]] && return ...
In Zsh, declare -F declares a double-precision floating point variable: $ declare -F myvar $ echo $myvar 0.0000000000 To list all function names in Zsh, use typeset -f +. In zsh, the $functions special associative array maps function names to their definition so ${(k)functions} which expands to the keys of that assoc...
`declare -F` does not work in zsh
1,478,106,400,000
I have aliased pushd in my bash shell as follows so that it suppresses output: alias pushd='pushd "$@" > /dev/null' This works fine most of the time, but I'm running into trouble now using it inside functions that take arguments. For example, test() { pushd . ... } Running test without arguments is fine. But wit...
Aliases define a way to replace a shell token with some string before the shell event tries to parse code. It's not a programming structure like a function. In alias pushd='pushd "$@" > /dev/null' and then: pushd . What's going on is that the pushd is replaced with pushd "$@" > /dev/null and then the result parsed. ...
$@ in alias inside script: is there a "local" $@?
1,478,106,400,000
I have a script using a pretty long pipe quite a lot of times. The middle of each pipe is the same command chain. Only the beginning and the end defers all the time it is used. Different-command-1 | command A | command B | command C | diff-cmd-2 is there a way to call this commands as a function within the pipe? ...
The commands in a function run with the same stdin and stdout as the function itself, so we can just put a pipeline in a function, and the stick the function in another pipeline, as it if were any other command: func() { tr a x | tr b x } echo abc | func | tr c x This prints xxx.
Calling a function within a pipe
1,478,106,400,000
Example $ echo "This is great" This is great $ num2=2 $ num3="Three" $ echo $num2 2 $ echo $num3 Three Redefining echo: $ echo(){ command echo "The command was redefined"; } $ echo $num2 The command was redefined $ echo $? The command was redefined So is this true? Are all commands in Unix shell functions and we can...
No, all Unix commands are not shell functions, but they may be overridden by a shell function. Shell function names are not restricted by the names of built-in or external utilities. Just as you may have several external utilities with the same name under different paths, you may also have a shell function or an alias...
Are functions equivalent to built in commands in the bash / shell scripting language?
1,478,106,400,000
Directory Structure: one.pdf ./subdir/two.pdf ./anothersubdir/three.pdf When I type: find ./ -type f -name "*.pdf" it retrieves all the pdfs, including subdirectories. Bash Function function getext {find ./ -type f -name "$1"} With this function in bashrc, typing: getext *.pdf It only retrieves "one.pdf" but...
For the same reason that you quote "*.pdf" in the arguments to find inside your function, you need to quote it when you call the function: getext "*.pdf" Otherwise, the shell will attempt to match *.pdf to filenames in the current directory resulting in it being expanded - in this case to one.pdf - before being passe...
Bash function does not work recurrsively [duplicate]
1,478,106,400,000
I know !! re-runs commands but what exactly would occur if I re-ran a command that had a variable in the command?
Well, let's try it: $ foo=bar $ echo $foo bar $ foo=qux $ !-2 echo $foo qux $ history ... 219 foo=bar 220 echo $foo 221 foo=qux 222 echo $foo 223 history So it appears that the command is added to history before variable expansion occurs.
Why must you be careful when using Bash's built in command history function to re-run previous commands that contain variables?
1,478,106,400,000
I am working on a highly portable script that users shall source to their shells, forcing me to use POSIX scripting. There are many useful functions in the script, one of them is special though, as it returns true or false status to the calling function. Now, I used to use return 0 in cases like this. But it appe...
true is portable, but doesn't by itself return. return true is not portable, and also doesn't work reliably. If you have a function like so: f() { true } Then yes, it will portably return from the function with an exit status of zero. When falling off from the end, the exit status of the last command is returned ...
Does `return 0` equal `true` (in sourced script to shell's environment)?
1,478,106,400,000
The behaviour of my shell environment changed: Earlier, when pasting a function definition e.g. function exampleFunc { echo hello } to the shell, it would display as formatted and register the new function definition. Now, for some reason, it displays with > before each line other than the first. function example...
This has nothing to do with you installing nushell. It also does not stop the shell from functioning correctly. The > is the default value of the shell's secondary prompt (PS2). The secondary prompt is displayed whenever the shell requires further input after the user has pressed the Enter key without completing th...
> symbol appearing when interactively defining function in bash
1,478,106,400,000
I have defined a test alias as: alias testalias='python3 -c "f = open(\"/tmp/testopenfile\", \"w+\"); f.write(\"hi\n\")"' It works fine when I run it directly through terminal. I can cat /tmp/testopenfile normally. I have also defined a helper function to background and mute error and output of programs. I thought of ...
Replace the alias with a function. testalias() { python3 -c 'f = open("/tmp/testopenfile", "w+"); f.write("hi\n")' } detach () { "$@" > /dev/null 2> /dev/null & } Bash only looks at the first word of a command for alias expansion, so the function gets the literal argument testalias. (I think zsh has "global" ...
How to evaluate bash alias before being passed to bash function?
1,478,106,400,000
I'm running an Abaqus job in Ubuntu command line using two files (file1.inp and file2.f) as follows: abaqus job=file1 user=file2.f Since I'm doing this a lot with different files, I wanted to make it easier as: myfunc file1 file2.f where myfunc is a bash function that takes the files names and run abaqus command aba...
myfunc () { abaqus job="$1" user="$2" } This calls abacus with arguments constructed from the two arguments given to the function. With a bit of error checking (making sure that the correct number of arguments is passed): myfunc () { if [ "$#" -ne 2 ]; then printf '%s: Expecting 2 arguments, got %s\n' "$...
Run a bash function that takes two files names as variables from command line
1,478,106,400,000
I have a script which writes some content into a file with cat and EOF. While this thing works within a bash script, it doesn't work if I put it inside a function. Working code: cat << EOF | sudo tee /etc/network/interfaces auto lo iface lo inet loopback auto eth0 iface eth0 inet dhcp EOF It's syntax highlighting (w...
The EOF here-doc marker must either be at the beginning of the line, or a full TAB character indented: someFunctions { sudo tee /etc/network/interfaces <<-'EOF' auto lo iface lo inet loopback auto eth0 iface eth0 inet dhcp EOF } I've removed the function keyword as it'...
sudo redirection doesn't work when in a function
1,478,106,400,000
I stored the following script in a file and created an alias to that file in the user's bashrc, then sourced that bashrc: #!/bin/bash domain="$1" && test -z "$domain" && exit 2 environment() { read -sp "Please enter the app DB root password:" dbrootp_1 && echo read -sp "Please enter the app DB root password...
I seem to have missed 2 semicolons (;) before the fi (the closure of the if statement). These are the correct if-then statements: if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched. Please try again." && exit 2; fi if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched. Please try again." && ex...
Syntax error near unexpected token `}' in a Bash function with an if-then statement [closed]
1,478,106,400,000
Tracking down strange behavior a bash script resulted in the following MWE: set -o errexit set -o nounset set -x my_eval() { eval "$1" } my_eval "declare -A ASSOC" ASSOC[foo]=bar echo success fails with: line 9: foo: unbound variable. Yet it works if eval is used in place of my_eval (and, obviously, if the declare ...
A glance at the man pages tells us: The -g option forces variables to be created or modified at the global scope, even when **declare** is executed in a shell function. Thus, if your script would say: my_eval "declare -gA ASSOC" it/you would be happier. The point is that the "declare" statement sees its scope at whe...
why doesn't eval declare in a function work in bash?
1,478,106,400,000
I need to set up a function in zsh that would edit a different file based on some input at the command line. I want to simplify my aliases so I don't have multiple aliases to do the same thing but with a slight variation. I am specifically trying to set up a function to open in my editor different versions of the php....
function editphpini() { local version=$( echo $1 | sed 's/^\(.\)/\1./' ) subl /usr/local/etc/php/${version}/php.ini } usage: % editphpini 54
ZSH function to edit a file based on an input at the cli
1,478,106,400,000
I want to retry a command for 5 times with an interval of 20 seconds. I want this command to be passed as a method parameter. How to do it? And once the function is written how to pass the value to the function? I want my current code to be converted to a function which takes a set of parameters. How to write and cal...
retry() { trialNumber=$1 delay=$2; shift 2 while [ "$trialNumber" -gt 0 ]; do "$@" && return ret=$? sleep "$delay" trialNumber=$(($trialNumber - 1)) done return "$ret" } retry 5 20 ssh "$USERID@$HOST" "$SCRIPT_LOCATION/runme.sh" Though the last sleep in case of failure is not necessary. May b...
Converting a loop of code to function
1,478,106,400,000
I'm attempting to write a function that writes arrays with a name that's passed in. Given the following bash function: function writeToArray { local name="$1" echo "$name" declare -a "$name" ${name[0]}="does this work?" } Running like this: writeToArray $("test") I get two errors: bash: declare...
You'd use a nameref for that: writeToArray() { local -n writeToArray_name="$1" writeToArray_name[0]="does this work?" } Testing: bash-5.0$ test[123]=qwe bash-5.0$ writeToArray test bash-5.0$ typeset -p test declare -a test=([0]="does this work?" [123]="qwe") With older versions of bash which didn't hav...
Bash create parameter named array within function
1,478,106,400,000
I have this simple script, which does nothing more than: check if an email matches a specific pattern in that case, add a tag to a taglist before quitting, print that taglist set -e lista_tag=() in_file="/tmp/grepmail-classify.txt" # save stdin to file, to use it multiple times cp /dev/stdin $in_file # CLASSIFY ...
classify '"grepmail -B "somepattern"' 'MYTAG' This is hard to get to work, for exactly the reasons mentioned in BashFAQ 050. But we can make it work if we put the "tag" argument first, since that allows us to use the rest for the command: #!/bin/bash lista_tag=() classify() { local tag="$1" shift res=$(...
How to pass commands around?
1,478,106,400,000
As pointed out in this question, the prototype for the ioctl function inside a Linux kernel module is: (version 1) int ioctl(struct inode *i, struct file *f, unsigned int cmd, unsigned long arg); or (version 2) long ioctl(struct file *f, unsigned int cmd, unsigned long arg); I would like to use them in a kernel modu...
Are both the above prototypes suitable in this case? If yes, why? If no, how to choose the right one? They are not both suitable. Only version 2 is currently available in the kernel, so this is the version that should be used. What header/source file(s) contain these prototypes? In other words: what is the offic...
Two different function prototypes for Linux kernel module ioctl
1,478,106,400,000
I'm new to bash. I'm confused about the way functions work in this language. I have written this code: #!/usr/bin/env sh choice_func() { echo "$choice" } echo "Enter your choice:" read choice choice_func While investigating my code, I realized that I have forgotten to send the value of choice as input when ...
You read a value into the variable choice in the main part of the script. This variable has global scope (for want of a better word), which means that it will be visible inside the function too. Note that if you were to read the value inside the function, then the variable would still have global scope and be visible...
Function can echo the value that has not received as input
1,478,106,400,000
I made a function in bash and when I call it, it crashes with an unbound variable error. I don't understand cause the variables that are said to be unbound are declared. Moreover, it seems to be triggered randomly like some times it crashes on line 66, some times it crashes on line 76 and some other times it crashes o...
This doesn't set a value for any of value, key or arg: declare value key arg So, if the assignment to key in the case isn't reached: while (( $# > 0 )); do arg="$1" && shift case "$arg" in --key=*) key="${arg#*=}" ;; then key will still be unset ("unbound") after the loop, and sin...
Random unbound variable error within function
1,478,106,400,000
I have been trying all day with no success to get bash to receive arguments: the closest reference to this I could find is: How to pass parameters to an alias? if i execute: rename -v -n 's/^the.//' * it does exactly what I need, but I would like to turn into into an alias that received "the." string at run time. I...
You can't use arguments in an alias. (You can append items after it, but that then just complicates this situation.) Here's what the man page (man bash) says about them: The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. [.....
bash alias rename function with arguments
1,478,106,400,000
I'm using bash shell on Ubuntu Linux. I have this in my script output_file=create_test_results_file "$TFILE1" Through echo statements, I have verified that the value of $TFILE1 is a file path, e.g. /tmp/run_tests.sh1.7381.tmp But when I run my script, somehow the contents of the file are being passed to my function...
The command line for calling your function: output_file=create_test_results_file "$TFILE1" This will assign the value create_test_results_file to the variable output_file before running the command "$TFILE1". I believe you might have wanted to do output_file=$( create_test_results_file "$TFILE1" ) This assigns the o...
How do I pass a file path to a function instead of the contents of the file?
1,478,106,400,000
This function essentially aims: alias "git log"="git log --name-status" had it been possible. Since it is not possible to alias something with spaces in it, I choose to write a shell function: git() { case $# in 1) case "$1" in log) git log --nam...
You're recursively calling git the function. Use command git for the internal calls so that the function isn't used for them.
Terminal emulator crashes with function with nested case statements?
1,478,106,400,000
What am I missing here? I have created a simple array: declare -a appArray=( "item1 -a -b" "item2 -c -d" ) If I echo this I can see it all echo ${appArray[@]} > item1 -a -b item2 -c -d I then create a function as follows: fc_DEBUG () { if [ $1 -eq 1 ] ; then echo $2; fi; }; It is de...
${appArray[@]} gets expanded before fc_DEBUG runs. So the second argument the function sees, is the first of the array. To be explicit, the three arguments fc_DEBUG sees, are $DEBUG "item1 -a -b" "item2 -c -d" (replace $DEBUG with the words resulting from the split+glob operator applied to the actual value of $DEBUG ...
display array in a function - not working
1,478,106,400,000
I studied this article called Returning Values from Bash Functions. Data Lorem. \begin{document} hello \end{document} Case #1 which does not work Code #!/bin/bash function getStart { local START="$(awk '/begin\{document\}/{ print NR; exit }' data.tex)" } START2=$(getStart) echo $START2 which returns falsel...
$(...) (aka "Command substitution") captures the output of the ... command. Assigning a value to a variable produces no output, so there's nothing to capture. In case #2, echo produces the output. getStart () { local l=Hallo echo $l } v=$(getStart) echo $v To answer your update: the function outputs Hallo. T...
Returning local values from Bash variables?
1,427,278,252,000
I have the following simple script. In this script, I am assigning a value to a global variable inside a function. I can clearly see that the value is being assigned to the variable via a debug statement. However, when I echo the variable at the end, it's always empty. function getValue() { local key=$1 local configFi...
You're expecting: CONFIG_RESULT=$(configuer) To assign a value to $RECYCLEBIN because you... RECYCLEBIN="$value" ... in the configuer() function. It's true that the function does assign a value to $RECYCLEBIN but that value only persists for the duration of the $(subshell) in which you set it. It will not apply any ...
Value assigned inside a function variable is always empty
1,427,278,252,000
I have a bash function called numeric that returns either 1 or 0. numeric () { # compute k either 1 or 0 echo "$k" } How can I use this function in a conditional statement to check if a variable var is numeric?
Remember that in the context of shell conditional expressions, a return value of 0 means "success" or "true", and a non-zero value means "failure" or "false", so I would recommend adapting the function so that it returns 0 if the argument is a numerical value. Assuming that the "conditional statement" is an if constru...
Use custom test function in bash conditional statement
1,427,278,252,000
This site says that functions are faster than aliases, but he rightly points out that aliases are easier to understand - when you want something very simple and do not need to consider passing arguments, aliases are convenient and sensible. That being the case, my personal profile is about 1,000 lines and serves both ...
Try something like this: $ cat find-dupes.pl #!/usr/bin/perl use strict; #use Data::Dump qw(dd); # Explanation of the regexes ($f_r...
Finding duplicate aliases and functions in a script (.bashrc etc)
1,427,278,252,000
In bash, when I'd like to have a glimpse at what an already defined shell function does, I can: $ type myFunctionName For a variable myFunctionName, it provides me with the type of the variable (a function), but also print the source of this shell function on the terminal. Very handy. When I do the same in zsh, it o...
For both zsh and bash (and ksh) you can use typeset -f myFunctionName to get the function definition % x() function> { function> echo x function> } % typeset -f x x () { echo x }
Is there a zsh command to output shell function code, like `type` in bash [duplicate]
1,427,278,252,000
within of my bash code I have a part of an sed + AWK code, which do interatively some operation on input file and add the results to another txt file (the both filles had been created by the same bash script, and can be stored as different variables). #sed removing some lines in input fille "${file}".xvg, defined in t...
Just change ${file} to "$1" inside your function and it'd do what you want. Also then consider changing this: bar_xvg_proc () { ##AWK procession of XVG file: only for bar plot; sed -i '' -e '/^[#@]/d' "$1" # check XMAX and YMAX for each XVG awk ' NR==1{ max1=$1 max2=$2 } $1>max1{max1=$1} $2>max2{max2=$...
bash: functions containing part of AWK code
1,427,278,252,000
I found (on Google) this perfectly working line to replace every occurences in all files in my directory and subdirectories: grep -lr previoustext | xargs sed -i 's/previoustext/newtext/g' It works great. But now I'm trying to use it in a function in my bash_aliases file as following: freplace() { grep -lr previo...
If you want to pass arguments to a function, you need to use positional parameters to pick them up. freplace() { grep -lr "$1" | xargs sed -i "s/$1/$2/g" } Note that it doesn't work for strings containing / or other characters special to sed.
bash function to replace every occurence of text in directory and subdirectories
1,427,278,252,000
I'd like to be able to have $SECONDS shown with hours, minutes, seconds in an environment variable, so I only need to use, e.g. $RUNTIME in various places in the script rather than have the whole thing every time I want to use it. I don't know what formatting to use to allow it to go into a variable: export RUNTIME="$...
Defining RUNTIME as a variable wouldn't help as it outputs a constant value, always, the run time when it was defined. Try a shell function in lieu: runtime() { printf "%dhrs %dmin %dsec\n" $((SECONDS / 3600)) \ $(((SECONDS / 60) % 60)) \ $(($SECONDS ...
Can I put $SECONDS into an environment variable in a bash script?
1,427,278,252,000
I want to pass arguments from a loop into a function func. For simplicity let's say we are working with the loop for x in {1..5} do for y in {a..c} do echo $x$y done done I'm just echoing because I don't know what to do. I'd like to run the equivalent of func 1a 1b 1c 2a 2b 2c 3a 3b 3c 4a 4b 4c 5a 5b ...
func {1..5} would be equivalent to func 1 2 3 4 5. In general, the list of words in a for statement is just like any list of words in a command, so you can just replace the loop with a single invocation of the command, with whatever list you used there moved to the command arguments. Also, you can use multiple brace e...
How to pass list of arguments into a function
1,427,278,252,000
I have a shell function (in .bashrc) which creates a temp file, executes the arguments (including all sequence of pipelines), redirects it to a temp file and then open it in VS Code. I invoke the shell function as Temp "ls | nl" In the follwoing code, I tried to make it work. I break the entire string with IFS as a s...
If you want a function to execute a shell command given as an argument, you'll need to use eval on the string, e.g. this prints FOO: eval_arg() { eval "$1" } eval_arg "echo foo |tr a-z A-Z" Just expanding "$1" won't do, since shell grammar like pipes, quotes and redirections aren't processed after parameter expan...
Shell Function: Sequence of Pipelines as Argument
1,427,278,252,000
I am writing a shell function which makes an external API call via cURL (the external API syntax isn't under my control). I've approached it like this (simplified): #!/bin/sh template_get_entry='get_entry:%s' template_set_entry='set_entry:%s=%s' curlheaders='-H stuff' curluri="https://www.domain.com:1234/api.php" #...
You could try to fill the format strings with zero length specifiers up to the maximum expected parameter count: template_get_entry='get_entry:%s %0.0s'
Using shell 'printf' where the format string is in a variable and doesn't have a fixed number of field placeholders?
1,427,278,252,000
I do not understand the following expression. function abc(){ .............. ............... [[ -f $filename]] && return 0 || return 1 } As per tutorial if there is a file exists with filename variable name then this function returns 1 otherwise it returns 0. I understand && || operator ,but how is this statement...
Both return statements on that last line of the function can be removed. [[ -f "$filename" ]] This is the last statement in the function with both return's removed (note the quoted variable expansion and the added space before ]]). The "exit value" of the function will be the result of this statement. If the file $f...
Return value of function in UNIX
1,427,278,252,000
Suppose, I have a directory called Titlepage that have many files named titlepage_1.pdf, titlepage_2.pdf ... titlepage_n.pdf and their tex files also. I have a bash function that alter two filenames.(e.g. $alterpdf 2 3 this command swap filename titlepage_2.pdf to titlepage_3.pdf. And does same thing for the correspon...
OK, here's a script that does something like what you want. #!/bin/bash NEWFILES=${1} INSERT_IDX=${2} PREFIX="titlepage_" # just in case prefixnum=${filebase//[^0-9]/} case $prefixnum in (*[![:blank:]]*) echo "invalid prefix, contains numbers"; exit 1;; esac # check input arguments if [ ! $# -eq 2 ]; then echo ...
How to make a function in bash that insert a new filename between others?
1,427,278,252,000
Below is the script i drafted, that will work based on the SIDs it will get from ps -ef | grep pmon Once the SID is grepped, it will pass the SID to dbenv() to set the necessary parameters, and it also cuts the DB_VERSION from /etc/oratab entries. Based on the version, if 12 or 11 then the script should execute a b...
This question probably belongs on https://codereview.stackexchange.com/ instead of here, but here are my recommendations: use $() rather than backticks for command substitution. you (almost) never need to pipe grep in to awk. For example, instead of: ps -eaf | grep pmon | grep -v grep | awk '{print $8}' you can do...
Execute a block based on the output of a variable [closed]
1,427,278,252,000
A function definition is a command. When a function definition is run, I thought that the function body would be kept intact, as if the function body is single quoted. I knew I was wrong, when I understood the following from the Bash manual in G-Man’s answer to my Alias and functions question: Aliases are expanded...
<rant> “running a function definition” and “running the definition of a function” are not common idioms.  I expect that most people would refer to that simply as “defining a function”.  OK, that phrase might be interpreted to refer to conceptually specifying the characteristics and interfaces (parameters and other i...
Which of the following shell operations are performed inside the function body when running a function definition and when calling a function?
1,427,278,252,000
Say I've got this: #!/bin/sh function show_help { cat<<% Usage: $0 [-h] % } # the following lines is pseudo-code if argument contains "-h" show_help otherwise do_stuff If I run ./test it does some stuff as intended, but if I run ./test -h, it produces Usage: show_help [-h] but I intended to let it produce Usag...
I can't reproduce this. The question is tagged with '/bash'. With bash, $0 is always the name of the script, so if this is in /tmp/test #!/bin/bash function show_help { cat <<% Usage: $0 [-h] % } show_help then bash /tmp/test gives me Usage: /tmp/test [-h]. If I use ksh93 /tmp/test I do get Usage: show_help [-h], due...
Get the name of the shell script from inside a function
1,427,278,252,000
Assume, I do archive several files with this functions: gen_password () { gpg --gen-random 1 "$1" | perl -ne' s/[\x00-\x20]/chr(ord($^N)+50)/ge; s/([\x7E-\xDB])/chr(ord($^N)-93)/ge; s/([\xDC-\xFF])/chr(ord($^N)-129)/ge; print $_, "\n"' } archive () { ARCHIVE_NAME="$1" PA...
Since your upload() function is expecting a parameter ($1) to use as the archived filename, pass it along in your commandline: archive foo.7z 1.rar pass.tar.gz d7432.png && upload foo.7z If foo.7z is a variable parameter for archive() as well, simply pass the same variable to upload(): archive $archivename 1.rar pass...
Pipe encrypted archive to uploader
1,427,278,252,000
In order to launch a new terminal and run a zsh function on it, I am trying to run the following command from within an urxvtc terminal (the urxvtd is running as a systemd service) urxvtc -e zsh -c "my-zsh-defined-function" which doesn't work as the function is unknown. I need to explicitly source my zshrc to ma...
It shouldn't, since you're not running zsh interactively. Quoting man zsh (section STARTUP/SHUTDOWN FILES): [I]f the shell is interactive, commands are read from /etc/zshrc and then $ZDOTDIR/.zshrc. You could try using -i: -i Force shell to be interactive. It is still possible to specify a script to e...
Why urxvtc doesn't accetp zsh functions when called with a "-c" argument?
1,427,278,252,000
What about use so solution? Functions run in loop (cycle?). In that loop - I have another function wuch also uses loop. When second function get NO answer from user - it send break 2 to stop loop and proceed main script actions. Function uses variables wich set in file. So, is it good idea use variables as parameters...
One alternative that might be cleaner is to have answer return 0 or return 1, depending on whether the user said yes or no. Then test the value of answer in the place where you call it, and only do the action if answer returned 0. Based on your earlier script, it would look something like this: while tomcat_running &...
Using break command as argument to function [closed]
1,427,278,252,000
I'm trying to write a find and cd function like so: findcd () { cd "$(dirname "$(find '$1' -type '$2' -name '$3')")" } to be called like so: find . f [FILE_NAME] But it's seeing the dollar sign and expecting more arguments as oppose to executing what's inside. I'm just starting with writing aliases and func...
Try this: findcd () { cd "$(dirname "$(find "$1" -type "$2" -name "$3")")" } The problem with your original attempt is that you had the variables single quoted so they were not being expanded. Also note that this will not work if you have more than one find result.
how to write function with nested commands [duplicate]
1,427,278,252,000
I'm trying to learn bash scripting using freeCodeCamp tutorial for beginners on YouTube. I'm stuck at the point where he shows how to create a function. He saved on a variable a command with an option #!/bin/bash showuptime(){ up=$(uptime -p | cut -c4-) since=$(uptime -s) cat << EOF ---------- This machi...
To clear a few things up: As variable of a function you would rather indicate the arguments passed to the function (none here) which are accessed via $1, $2, and so on. What you have are variables in your functions and because they are not marked local they are not even limited to the function. The $( ) construct is ...
How to store command with option on variable of a function in zsh?
1,427,278,252,000
I am attempting to write a function which will take two commands as inputs, time the executions of both of them, then output those times to a text file. After reading this post, I got most of the way there, and can write my execution times to a file one at a time. The problem I have now is getting the function to ac...
With: { time "$1" ; } 2> ~/file.txt With a shell such as bash that has time as a keyword, you're using the time keyword to time the evaluation of the "$1" shell code. "$1" is code that executes the command whose name is in the first position parameter to the function: With: timeDiff grep "str" file1 query databas...
Compare Execution Times of Two Functions
1,427,278,252,000
I have the following bash function that returns 0 when tho variable verbos is defined. Have read the bash manual which says that when return command return N, the N is omitted, the return status is that of the last command executed within the function. How can I use only return at the end, taking the value of N, depen...
This should work tesverbos () { vb="${verbos+vbset}" test -n "$vb" }
Using bash return depending on return status of last command executed within a function
1,427,278,252,000
Have added a number of functions which I source from my .bashrc. For instance, I use export -f calc I also have another function usage_calc where I comment out the export call # export -f usage_calc But I can still call usage_calc. What is happening?
You're using bash as your shell. The function is defined in or via your .bashrc, which makes the function available to your shell. The export has no relevance
Calling a function from terminal without export from sources file [duplicate]
1,427,278,252,000
I've got a function defined in my fish shell: function cl --wraps=cd cd $argv && ls -l --color=auto end According to man function, the --wraps option "causes the function to inherit completions from the given wrapped command." However, when I type cl and start to tab-complete, I'm shown options which include non...
You're hitting this issue which was fixed in fish shell version 3.3.0. Upgrade to a newer fish and it should fixed.
Function tab-completion not matching that of wrapped command
1,427,278,252,000
I've the following code on myscript.sh for the purpose of execute function on a file with .md extension when this file is modified: function my_function(){ echo "I\'ve just seen $1" } typeset -fx my_function find . -name "*.md" | entr -r -s "my_function $0" entr documentation: * [...] the name of the firs...
You are calling entr from a shell script. When the shell performs variable substitution (or parameter expansion in the manual), $0 will expand to the filename of the script. To protect the $0 from variable substitution by the shell, use \: find . -name "*.md" | entr -r -s "my_function \$0" Edit: As @roaima reminded, ...
Use file marker with entr
1,427,278,252,000
I'm running Ubuntu on WSL2. I frequently download zipped homework files from my school's website. They go into my Downloads folder on Windows. I want them copied into a particular path on my Linux filesystem, unzipped, and then renamed to put my name in front of the filename. This is what I have so far: params: $1: fi...
With bash, use substitution with % char to remove end of content: $ file="myfile.zip" $ echo "${file%.zip}" myfile You could use wildcard: $ file="myfile.zip" $ echo "${file%.*}" myfile You could maximize motif with double %: $ file="myfile.tar.gz" $ echo "${file%.*}" myfile.tar $ echo "${file%%.*}" myfile
access name of unzipped file inside a function
1,427,278,252,000
So I have a function that I wish to run from my command line. cat foo.sh #!/bin/bash echo foobar I export it to my PATH variable and change to a different directory. export PATH=${PATH}:/home/usr/scripts/foo.sh mkdir test && cd test sh foo.sh sh: foo.sh: No such file or directory If i run it like so foo.sh I get b...
Several issues here. The $PATH consists of colon-separated directories, not files. You shouldn't declare a script as a bash script and then use sh to run it. Generally speaking, a file that you're going to call as if it were a standard utility wouldn't have an extension. (Extensions are optional in many situations any...
Unable to run file from command line after adding to PATH
1,427,278,252,000
I am looking for a way to simplify the different php versions and also paths of Composer. I found an approach in this answer that looks very appropriate for me. I have tried to implement the following for understanding function composer () { if [ "$PWD" == "/home/vhosts/domainName/httpdocs" ]; then /usr/bin...
Pass the arguments of the function on to the program you call from the function: composer () { if [ "$PWD" = "/home/vhosts/domainName/httpdocs" ]; then /usr/bin/php7.3 lib/composer "$@" elif [ "$PWD" = "/home/vhosts/domainName2/httpdocs" ]; then /usr/bin/php5.6 composer.phar "$@" else ...
Path dependent commands in .bashrc
1,427,278,252,000
It is known that parsing the output of ls is generally a bad idea and one solution is to use globbing instead of ls to 'safely' loop through files in a directory. for path in /path/to/search/*; do ... # Do more filtering ... echo "$path" done This function will further filter some of the results that ...
No, you can't reuse the loops output as you have show as that replicates the issue with ls exactly, as well as adds issues with echo possibly interpreting backslashes in filenames. Instead, if you're using a shell language that has arrays and name references (like in bash 4.3+), you can do it slightly differently: myg...
Using paths from a function that uses globbing
1,427,278,252,000
I have written a below block of code #!/bin/bash TABLE_NAME="${1}" COL_NAME="${2}" FIELD_VALUES_1SQ_FUNC() { FIELD_VALUES_1SQS=`sqlplus -s sab/admin@TERM << EOF SET FEEDBACK OFF; SET HEADING OFF; Select TESTING.FIELD_VALUES_TEMP_1SQ.NEXTVAL from dual; exit; EOF` FIELD_...
What you're looking for is called a while loop. Consider this simple example: n=0 while [ $n -lt 5 ]; do echo Not done yet n=$(($n+1)) done A while loop does two things, and by implication the programmer must do a third thing. The while loop tests the condition: is n less than 5? If the condition is true, then:...
Iterate the if else statement until a condition is success
1,427,278,252,000
I’m trying to create a ls-like function. I started with this alias, which works fine: alias l="/usr/bin/ls -lF --color=always | tr -s ' ' | cut -d ' ' -f 9-" However, converting it to a function results in no colors: l() { local _c= [ -t 1 ] && _c=--color=always /usr/bin/ls -lF $_c "$@" | tr -s ' ' | cut ...
Are you sure you haven't got an l alias that is either interfering with the function definition or being used before the function: aliases take precedence over functions. And are expanded even for a function definition.
escape sequence behaving differently in function
1,427,278,252,000
Sometimes when I'm copying and pasting a command from a site, I accidently copy the leading "$" or "#" by accident. Is there a Fish Function I could make that would check if one of those is included in a command and automatically remove it before running it? For example, if I copy and paste $ sudo apt install foo bar...
Sure: function '$'; eval $argv; end Then myprompt$ $ echo hello world hello world
Is there a Fish Function I can make to eliminate leading "$"/"#" from commands copied from sites?
1,427,278,252,000
I am in the process of writing bioinformatics pipelines. These pipelines take in input files and pass them through multiple packages. Say there is a list of files that goes file1, file2, file3... file n, and for each I want to apply a function that goes function1 -file 1| function 2 | function 3 > file 1.output but ...
According to the information in your question, this should do what you requested: for i in file1 file2 file3 file4 fileN do function1 "$i"| function2 | function3 > "$i".output done
Creating a function that reads off an input list of files
1,427,278,252,000
I’m working on a function this works but it is ugly. One thing that could be changed is being able to know the name of the screen. Using screen -dms minecraft java ….jar now starts a screen session named with what appears to be random numbers..hostname. Next is the voodoo that happens to strip the name from screen ...
You're using a lot of variables and a log file unnecessarily. I'm not sure about the stuff after stuff, but I bet it can be simpler: say_this() { local name="$(ssh -p 8989 192.168.1.101 screen -ls | awk 'NR==2 {print $1}')" echo "$1" ssh -p 8989 192.168.1.101 screen -S "$name" -p 0 -X stuff "$1" }
Ugly bash function to send commands and "say" anything in screen over ssh. Is there a better way?
1,384,859,076,000
I tried to have a switch if either an option is set or not while getopts "s:u:d:e:ch" _OPTION; do case $_OPTION in ... c) isCSet="Y" then I'm calling my function : myFunction $isCSet then in my function I'm doing : echo $1 but I don't have anything in. How can I ...
You might be missing to initialize isCSet, eg: isCSet=N while getopts s:u:d:e:ch _OPTION; do case $_OPTION in ... c) isCSet=Y;; ...
Using variable in KSH function
1,384,859,076,000
I tried to write a small ksh script: fDestExists (){ cd /tmp read vANSWER?" >> Do you want to create a repository in pwd ? Type YES or NO" echo " |----> $(fGetDatum) You typed: " $vANSWER if [ "$vANSWER" = "YES" ]; then read vANSWER2?" >> Type your repository's name....
1: you can directly use the PWD variable, eg: echo " |----> Logs will be coped in $PWD." 2: $? is used to retrieve the last command return value which is numerical. There is no way to pass a string here, the return value should be 0 meaning success or something different meaning some failure. Use return 0 or retur...
Function, return value using pwd in KSH
1,384,859,076,000
The following (nested) function/s function hpf_matrix { # Positional Parameters Matrix_Dimension="${1}" Center_Cell_Value="${2}" # Define the cell value(s) function hpf_cell_value { if (( "${Row}" == "${Col}" )) && (( "${Col}" == `echo "( ${Matrix_Dimension} + 1 ) / 2" | bc` )) then echo "${Cent...
In the large script, in which the above function was integrated to work as part of it, and prior of defining the hpf_matrix function, the IFS has been changed to IFS=, without taking care to reset it back before using the unquoted command substitution in the function! An explanation on Using unquoted command substitut...
Why does a working standalone nested function/script not work inside a larger script? [duplicate]
1,384,859,076,000
I have a bash script set up to monitor a number of UDP streams and convert it into actionable data. My problem is that I need to set the script to periodically check to see if the stream capture is running and restart it if it isn't. The challenge is to create a new process name or ID for each stream capture and chec...
The name of a process on Linux at least is changed every time the process executes a command, but is changed to the basename of the file that is executed, not to the argv[0] that bash allows passing with exec -a. pgrep can match on the arg list (joined with spaces) with the -f option though, but note that like for gre...
Running a function as process with a set process name or id
1,384,859,076,000
With the following function I want to be able to call it with nico-usage or with a numeric value to print a different string. Con this be cleaned up or made easier. nico-usage () { local docstrg_lang=" {-V, --version}, {-u, --usage}, {-h, --help} -s SCAL, --scale SCAL" local docstrg_usage=" nicolaus -s 0.5 ...
If the question is how to make it pretty, here is a variant: nico-usage () { if (( $1 == 2 )) ; then echo -e "\nnicolaus -s 0.5 -aq 3" else echo -e "\n{-V, --version}, {-u, --usage}, {-h, --help} -s SCAL, --scale SCAL" fi }
function that allows different outputs dependent on argument values
1,384,859,076,000
Let's say I have two files main.sh and sub.sh in the same folder with the following contents: main.sh: #!/usr/bin/env bash export PARAMETER="main" my_func(){ echo "$PARAMETER $1" } export -f my_func # Run the other script ./sub.sh sub.sh: #!/usr/bin/env bash PARAMETER="sub" my_func $PARAMETER If we run main.sh,...
You can create functions with parameters already expanded. And as you can overwrite them later (globally or in a subshell) you can kind of "export them with parameters already expanded". #!/usr/bin/env bash export PARAMETER="main" eval "my_func(){ echo \"$PARAMETER \$1\" }" export -f my_func # Run the other scri...
Is there a way to export functions with parameters already expanded?
1,384,859,076,000
I have a function plist that is able to call head and tail commands. But for processing regions I call a different function pregion. # --- plist --- ("-H"|"--head") local -r hn="$2" ; shift 2 ;; ("-T"|"--tail") local -r tm="$2" ; shift 2 ;; ("--FS") # field separator loca...
Copy the orginal args to an array, and use that with pregion. e.g. plist() { local -a origargs=("$@") ... case ... esac ... if ... elif [[ -v dyn ]]; then pregion "${origargs[@]}" fi
Bash function calling another function that requires passing user-defined options
1,384,859,076,000
So I am trying to sort files with specific extensions into specific folder (ones that have been chosen by user by command line arguments) Lets say $1 (.jpg) $2 (.docx) etc The script is all working and fine, but I am trying to write a loop that sorts these files into their folders (just simply based on their extensio...
You don't need an index to the arguments... Just do for file in "$@" do # apply command to "$file" done # work here on remaining files in directory The $file variable will take the successive values of your input arguments. Note the "$@" syntax, this insures that if arguments (file names) contain spaces they will ...
Using loop in script for command line arguments
1,384,859,076,000
I have the following function in a bash script: testcur.sh : #!/bin/bash function valcurl { if [[ $1 != "" ]] then tbl=$2 # can be multiple values data=/home/data btic=$data/$tbl"_btic" kline=$data/$tbl"_kline" if [[ "$1" == "btic" ]] then errbtic=$data/$...
It seems that you want the error output to go to a specific file depending on one of the arguments to your function. For this, you don't need two separate variables: if [[ "$1" == "btic" ]]; then err="$data/${tbl}_btic_err" elif [[ "$1" == "kline" ]]; then err="$data/${tbl}_kline_err" fi or just err="$data/$...
Shell script: Call variable with parameters/arg
1,384,859,076,000
I created a function to log the results of a script and added an argument to the script. You may look at it at https://docs.laswitchtech.com/doku.php?id=documentations:linux:pxelinux In this script, I added an argument --screen to launch the same script with all the arguments into a screen with the -L switch. Enable_...
I found a solution to my issue by testing the following 3 arguments if they contained -- in them. And since in this case I was looking for IPs and mask, I added a second test for that. So the first if validates that the following arguments are not functions in the script and then the second if validates the arguments ...
how to remove characters from variables to remove --function option1 option2
1,384,859,076,000
I am creating an shell application that do a lot of questions and I am using the read -p "<my_question>" <myvar> several times. The problem is that I also want to verify if answers is empty. So, I wondered to create a generic function to ask and verify if it is empty or not. If so, call the function itself recursively...
I would like to share something that I've discovered late. I've tried to add a further step in the answer validation: validate also if the path exists, and I could not adapt the Rakesh Sharma solution for this. Finally, I found exactly what I was looking for, that is a way to deal with "dynamic variable", and the real...
Create generic function to ask a question and verify if answer is empty
1,384,859,076,000
I am writing a script which displays input options in a while loop provided by a function user_input() and set values depending on user input, then I call another function user_info(). If a user made a mistake I am trying to offer him to go back to correct his input. So if a user set $var by mistake to "Yes" he can go...
I think I found a solution by adding return after each call of the user_input() function like this, please correct me if I made a mistake. Thanks a lot: user_input(){ while true; do input option $var done user_info } user_info(){ some code if [ "${var}" = "Yes" ]; then code (1) ...
resume running a script after function call
1,384,859,076,000
I'm new to shell programming and I have created a script that opens a connection to a server of mine. I want to have this script listen for an input from a client node and use that to run a function. This is my process. Run script > opens listener > on second computer use netcat to connect > run a function in the scr...
I got it figured out. I did indeed need a while statement. openSocket while read -r value; do val=${value:10} if [[ "$value" == playermsg* ]]; then val=${value:10} playermsg $val elif [[ "$value" == servermsg* ]]; then val=${value:10} servermsg $val else echo "...
netcat daemon for calling functions in sh script
1,384,859,076,000
Not sure why this is producing error. This is a test code emulating my real code. I want to write a wrapper for find and want to allow for any argument, so I'm wrapping each arg in single quotes. #!/bin/bash function find2 { ARGS="/usr/bin/find" while [[ $# -gt 0 ]]; do ARGS="$ARGS '$1'" shift ...
(in Bash) You can change to an array of values: find2() { ARGS="/usr/bin/find" ARGS+=( "$@" ) echo CALLING: "${ARGS[@]}" "${ARGS[@]}" } find2 /tmp/test -name "hello.c" But this works and is quite simpler: find2() { ARGS=( "/usr/bin/find" "$@" ) echo CALLING: "${ARGS[@]}" "${ARGS[@]}" ...
bash script function argument problem [duplicate]
1,331,066,898,000
I've just set up a new machine with Ubuntu Oneiric 11.10 and then run apt-get update apt-get upgrade apt-get install git Now if I run git --version it tells me I have git version 1.7.5.4 but on my local machine I have the much newer git version 1.7.9.2 I know I can install from source to get the newest version, but I...
You have several options: Either wait until the version you need is present in the repository you use. Compile your own version and create a deb. Find a repository that provides the version you need for your version of your distribution(e.g. Git PPA). If you don't need any particular feature from the newer version, s...
How can I update to a newer version of Git using apt-get?
1,331,066,898,000
Is there a way to color output for git (or any command)? Consider: baller@Laptop:~/rails/spunky-monkey$ git status # On branch new-message-types # Changes not staged for commit: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) ...
You can create a section [color] in your ~/.gitconfig with e.g. the following content [color] diff = auto status = auto branch = auto interactive = auto ui = true pager = true You can also fine control what you want to have coloured in what way, e.g. [color "status"] added = green changed = red bold ...
How to colorize output of git?
1,331,066,898,000
I have a script which runs rsync with a Git working directory as destination. I want the script to have different behavior depending on if the working directory is clean (no changes to commit), or not. For instance, if the output of git status is as below, I want the script to exit: git status Already up-to-date. # On...
Parsing the output of git status is a bad idea because the output is intended to be human readable, not machine-readable. There's no guarantee that the output will remain the same in future versions of Git or in differently configured environments. UVVs comment is on the right track, but unfortunately the return code ...
Determine if Git working directory is clean from a script
1,331,066,898,000
Is there a similar piece of software to SourceTree, a GUI for git, for Linux? I know about Giggle, git cola, etc. I'm looking for a beautiful, easy to use GUI for git.
A nice alternative is SmartGit. It has very similar features to SourceTree and has built in 3-column conflict resolution, visual logs, pulling, pushing, merging, syncing, tagging and all things git :)
GUI for GIT similar to SourceTree
1,331,066,898,000
I'm trying to create a user without password like this: sudo adduser \ --system \ --shell /bin/bash \ --gecos ‘User for managing of git version control’ \ --group \ --disabled-password \ --home /home/git \ git It's created fine. But when I try to login under the git user I'm getting the password ...
You've created a user with a “disabled password”, meaning that there is no password that will let you log in as this user. This is different from creating a user that anyone can log in as without supplying a password, which is achieved by specifying an empty password and is very rarely useful. In order to execute comm...
Creating a user without a password
1,331,066,898,000
In a git repository, I have set up my .gitmodules file to reference a github repository: [submodule "src/repo"] path = src/repo url = repourl when I 'git status' on this repo, it shows: On branch master Your branch is up-to-date with 'origin/master'. Changes not staged for commit: (use "git add <file>..." ...
It's because Git records which commit (not a branch or a tag, exactly one commit represented in SHA-1 hash) should be checked out for each submodule. If you change something in submodule dir, Git will detect it and urge you to commit those changes in the top-level repoisitory. Run git diff in the top-level repository...
Git submodule shows new commits, submodule status says nothing to commit
1,331,066,898,000
I have a git mirror on my disk and when I want to update my repo with git pull it gives me error message: Your configuration specifies to merge with the ref '3.5/master' from the remote, but no such ref was fetched. It also gives me: 1ce6dac..a5ab7de 3.4/bfq -> origin/3.4/bfq fa52ab1..f5d387e 3.4/master ->...
Check the branch you are on (git branch), check the configuration for that branch (in .../.git/config), you probably are on the wrong branch or your configuration for it tells to merge with a (now?) non-existent remote branch.
git pull from remote but no such ref was fetched?
1,331,066,898,000
I want to put my home directory (~) under source control (git, in this case), as I have many setting files (.gitconfig, .gitignore, .emacs, etc.) in there I would like to carry across machines, and having them in Git would make it nice for retrieving them. My main machine is my MacBook, and the way that OS X is set ...
I have $HOME under git. The first line of my .gitignore file is /* The rest are patterns to not ignore using the ! modifier. This first line means the default is to ignore all files in my home directory. Those files that I want to version control go into .gitignore like this: !/.gitignore !/.profile [...] A trickier...
Tips for putting ~ under source control
1,331,066,898,000
I want to copy my c directory with all subdirectories excluding ./git subdirectory. I do it using rsync : echo "copy c and sh files " rsync -a --include='*.c' --include='*.sh' --include='*/' --exclude='*' ~/c/ ~/Dropbox/Public/c # remove .git directory = do not send it to dropbox. Thx to Tomasz Sowa rm -rf ~/Dropbox/P...
Just add an explicit exclude for .git: rsync -a --exclude='.git/' --include='*.c' --include='*.sh' --include='*/' --exclude='*' ~/c/ ~/Dropbox/Public/c Another option is to create ~/.cvsignore containing the following line along with any other directories you'd like to exclude: .git/
How to use rsync to backup a directory without git subdirectory
1,331,066,898,000
When I do git push I get the command prompt like Username for 'https://github.com': then I enter my username manually like Username for 'https://github.com': myusername and then I hit Enter and I get prompt for my password Password for 'https://[email protected]': I want the username to be written automatically ...
Actually what you did there is setting up the author information, just for the commits. You didn't store the credentials. credentials can be stored in 2 ways: using the git credential functions: https://git-scm.com/docs/git-credential-store change the origin url to "https://username:[email protected]". a third altern...
Storing username and password in Git
1,331,066,898,000
I performed a git commit command and it gave me the following reply: 7 files changed, 93 insertions(+), 15 deletions(-) mode change 100644 => 100755 assets/internal/fonts/icomoon.svg mode change 100644 => 100755 assets/internal/fonts/icomoon.ttf mode change 100644 => 100755 assets/internal/fonts/icomoon.woff I know f...
The values shown are the 16-bit file modes as stored by Git, following the layout of POSIX types and modes: 32-bit mode, split into (high to low bits) 4-bit object type valid values in binary are 1000 (regular file), 1010 (symbolic link) and 1110 (gitlink) 3-bit unused 9-bit unix permissio...
File permission with six octal digits in git. What does it mean?
1,331,066,898,000
I found a collection of slackbuilds, some i need there are on GitHub. https://github.com/PhantomX/slackbuilds/ I don't want to get all git. git clone https://github.com/PhantomX/slackbuilds.git But only get a slackbuild, for this one. How to do this? Is it possible?
You will end up downloading the entire history, so I don't see much benefit in it, but you can checkout specific parts using a "sparse" checkout. Quoting this Stack Overflow post: The steps to do a sparse clone are as follows: mkdir <repo> cd <repo> git init git remote add -f origin <url> I'm going to interrupt her...
Is it possible to clone only part of a git project?
1,331,066,898,000
In order to get coloured output from all git commands, I set the following: git config --global color.ui true However, this produces an output like this for git diff, git log whereas commands like git status display fine Why is it not recognizing the escaped color codes in only some of the commands and how can I fi...
You're seeing the escape sequences that tell the terminal to change colors displayed with the escape character shown as ESC, whereas the desired behavior would be that the escape sequences have their intended effect. Commands such as git diff and git log pipe their output into a pager, less by default. Git tries to te...
git diff displays colors incorrectly
1,331,066,898,000
I feel like a kid in the principal's office explaining that the dog ate my homework the night before it was due, but I'm staring some crazy data loss bug in the face and I can't figure out how it happened. I would like to know how git could eat my repository whole! I've put git through the wringer many times and it's ...
Yes, git ate my homework. All of it. I made a dd image of this disk after the incident and messed around with it later. Reconstructing the series of events from system logs, I deduce what happened was something like this: A system update command (pacman -Syu) had been issued days before this incident. An extended net...
How did `git pull` eat my homework?
1,331,066,898,000
If I tar a folder that is a git repository, can I do so without including the .git related files? If not, how would I go about doing that via a command?
Have a look at git help archive or git archive --help. The git subcommand archive allows you to make archives containing only files trackeod by git. This is probably what you are looking for. One of many examples listed at the end of the manual: git archive --format=tar.gz --prefix=git-1.4.0/ v1.4.0 >git-1.4.0.tar.gz ...
Tar a folder without .git files?
1,331,066,898,000
I have for many years had my entire $HOME directory checked into subversion. This has included all my dotfiles and application profiles, many scripts, tools and hacks, my preferred basic home directory structure, not a few oddball projects and a warehouse worth of random data. This was a good thing. While it lasted. B...
Yes, there is at least one major pitfall when considering git to manage a home directory that is not a concern with subversion. Git is both greedy and recursive by default. Subversion will naively ignore anything it doesn't know about and it stops processing folders either up or down from your checkout when it reaches...
Are there pitfalls to putting $HOME in git instead of symlinking dotfiles?
1,331,066,898,000
I'm using git. I did a normal merge, but it keeps asking this: # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. And even if I write something, I can't exit from here. I can't find docs explaining this. How should I do?
This is depend on the editor you're using. If vim you can use ESC and :wq or ESC and Shift+zz. Both command save file and exit. You also can check ~/.gitconfig for editor, in my case (cat ~/.gitconfig): [user] name = somename email = [email protected] [core] editor = vim excludesfile = /home/mypath/.gi...
How to exit a git merge asking for commit message?
1,331,066,898,000
How do I remove a file from a git repositorie's index without removing the file from the working tree? If I had a file ./notes.txt that was being tracked by git, I could run git rm notes.txt. But that would remove the file. I'd rather want git just to stop tracking the file.
You could just use git rm --cached notes.txt. This will keep the file but remove it from the index.
How to remove a file from the git index
1,331,066,898,000
I have a regex I stuck in my .gitignore similar to: (Big|Small)(State|City)-[0-9]*\.csv It didn't work so I tested it against RegexLab.NET. I then found the gitignore man page which led me to learn that gitignore doesn't use regexes, but rather fnmatch(3). However, fnmatch it doesn't seem to have an equivalent of t...
There's no way to express this regular expression with the patterns that gitignore supports. The problem is not the lack of capture groups (in fact, you are not using capture groups as such), the problem is the lack of a | operator. You need to break this into four lines. BigState-[0-9]*.csv SmallState-[0-9]*.csv BigC...
What is the .gitignore pattern equivalent of the regex (Big|Small)(State|City)-[0-9]*\.csv
1,331,066,898,000
─[$] cat ~/.gitconfig [user] name = Shirish Agarwal email = [email protected] [core] editor = leafpad excludesfiles = /home/shirish/.gitignore gitproxy = \"ssh\" for gitorious.org [merge] tool = meld [push] default = simple [color] ui = true status = auto branch = auto Now I w...
Using SSH The common approach for handling git authentication is to delegate it to SSH. Typically you set your SSH public key in the remote repository (e.g. on GitHub), and then you use that whenever you need to authenticate. You can use a key agent of course, either handled by your desktop environment or manually wit...
how to set up username and passwords for different git repos?
1,331,066,898,000
I would like to keep track of changes in /etc/ Basically I'd like to know if a file was changed, by yum update or by a user and roll it back if I don't like the chage. I thought of using a VCS like git, LVM or btrfs snapshots or a backup program for this. What would you recommend?
It sounds like you want etckeeper from Joey Hess of Debian, which manages files under /etc using version control. It supports git, mercurial, darcs and bazaar. git is the VCS best supported by etckeeper and the VCS users are most likely to know. It's possible that your distribution has chosen to modify etckeeper so...
How to keep track of changes in /etc/
1,331,066,898,000
I have the following call structure: Jenkins runs fab -Huser@host set_repository_commit_hash:123abc. set_repository_commit_hash runs git fetch with pty = False. The child process ssh [email protected] git-upload-pack 'user/repository.git' never finishes. I've tried running git fetch in a local clone and that succeed...
This problem appears to have gone away on its own, as can be expected by a rapidly evolving piece of software. Since I have not observed this issue for probably a couple years now I'd like to extend my thanks to whoever fixed it and consider this question obsolete. If you are experiencing this issue with recent Git ve...
git-upload-pack hangs indefinitely
1,331,066,898,000
I've found tons of sites that explain how to have git warn you when you're changing line endings, or miscellaneous other techniques to prevent you from messing up an entire file. Assume it's too late for that -- the tree already has commits that toggle the line endings of files, so git diff shows the subtraction of th...
For diff, there's git diff --ignore-space-at-eol, which should be good enough. For diff and blame, you can ignore all whitespace changes with -w: git diff -w, git blame -w. For git apply and git rebase, the documentation mentions --ignore-whitespace. For merge, it looks like you need to use an external merge tool. You...
Ignore whitespaces changes in all git commands
1,331,066,898,000
I'm getting a bizarre error message while using git: $ git clone [email protected]:Itseez/opencv.git Cloning into 'opencv' Warning: Permanently added the RSA host key for IP address '192.30.252.128' to the list of known hosts. X11 forwarding request failed on channel 0 (...) I was under the impression that X11 wasn't...
It looks like you have ssh configured to always attempt to use X11 forwarding. The error message is GitHub telling you that you can't do X11 forwarding from their servers. Look for ForwardX11 yes in ~/.ssh/config or /etc/ssh/ssh_config and set it to no. This will prevent ssh from attempting to use X11 forwarding for e...
"X11 forwarding request failed" when connecting to github.com
1,331,066,898,000
Is there a way to make tree not show files that are ignored in .gitignore?
This might help: list git ignored files in an almost-compatible way for tree filter: function tree-git-ignore { # tree respecting gitignore local ignored=$(git ls-files -ci --others --directory --exclude-standard) local ignored_filter=$(echo "$ignored" \ | egrep -v "^#.*$|^[[:space:]]*...
Have tree hide gitignored files