date
int64
1,220B
1,719B
question_description
stringlengths
28
29.9k
accepted_answer
stringlengths
12
26.4k
question_title
stringlengths
14
159
1,472,032,051,000
I can print the current git commit sha1 in bash using this command: git rev-parse --short HEAD But how can I print only the latest commit message/title of the HEAD?
I quite like git show --oneline -s HEAD If you only want to see the message, use git show --pretty=format:%s -s HEAD instead. To add the SHA-1: git show --pretty=format:"%H %s" -s HEAD (or %h for the abbreviated SHA-1). See the git show documentation for details.
How to print only git message/title using bash script?
1,498,581,374,000
I tried this way: pushOut=`git push` But when I try: echo $pushOut I get an empty string
git push prints to stderr, apparently, so redirect stderr to stdout: $ a=$(git push 2>&1) $ echo "$a" Everything up-to-date
How to set a variable to the output `git push` command
1,498,581,374,000
My Oh-my-zsh does the following: When I run the git log --pretty --oneline command, it shows me a long list of commits, as expected. As soon as I hit q, it suddenly disappears with the below output: $ git log --pretty --oneline FAIL: 141 Why is this happening, and how do I fix it?
The number after “FAIL” is the process's exit status. A process's exit status, as reported by the shell, is generally¹: 0 if the program exited normally and reported a success. 1 to 125 if the program exited normally and reported an error. 128+s if the program was killed by signal s, where s is a small integer. 141 means signal 13 which is SIGPIPE. Under the hood, the git command sets up a pipe between two subcommands: one subcommand gathers data and writes data to the pipe, and the other subcommand is the pager less. If you don't view the whole output, the pager exits without waiting for the first subcommand to exit. When the first subcommand next tries to write to the pipe, it is killed by SIGPIPE. This is normal behavior, to avoid having commands continue to calculate and write output that nothing is reading. There's nothing to fix. But if you find this distracting, you can change your theme to not report a failure status when it's SIGPIPE. The way to do that depends on your oh-my-zsh theme, but from what I can see with a quick look (I don't use oh-my-zsh), the ones that have the word FAIL do it by setting the PROMPT variable, using a prompt expansion conditional to only print the FAIL stuff if the command's exit status is nonzero. So you'd need to change that to also take the “no-failure” branch if the exit status is 141. If you're using a theme bundled with oh-my-zsh, look for FAIL in the theme definition ~/.oh-my-zsh/themes/$ZSH_THEME.zsh-theme. Let's take the example of dst.zsh-theme: the definition is PROMPT='%(?, ,%{$fg[red]%}FAIL%{$reset_color%} ) %{$fg[magenta]%}%n%{$reset_color%}@%{$fg[yellow]%}%m%{$reset_color%}: %{$fg_bold[blue]%}%~%{$reset_color%}$(git_prompt_info) $(prompt_char) ' (Note that it spans multiple lines.) The general pattern is %(?,IFSUCCESS,IFFAILURE) to print IFSUCCESS on success ($? equals 0) and IFFAILURE on failure (including signals). So we'll add another condition if $? equals 141: PROMPT='%(141?, ,%(?, ,%{$fg[red]%}FAIL%{$reset_color%} )) %{$fg[magenta]%}%n%{$reset_color%}@%{$fg[yellow]%}%m%{$reset_color%}: %{$fg_bold[blue]%}%~%{$reset_color%}$(git_prompt_info) $(prompt_char) ' (Note that in addition to prepending %(141?, ,, there's a matching closing parenthesis on the second line.) ¹ The details are off-topic here.
Oh-my-zsh deletes output of successful command with "FAIL: 141"
1,498,581,374,000
I'm working on a CentOS 7.9 GNU/Linux system. I've built and installed a newer version of git (2.34.1 instead of 1.8.3.1 that's bundled with the distribution) under /opt/git/2.34.1, with a symlink to that directory at /opt/git/current; and I've added that symlinked directory to (the beginning of) my $PATH variable. Unfortunately, when I try the checkout a repository with an HTTPS URL, I get a few errors $ git clone https://github.com/eyalroz/cuda-api-wrappers.git Cloning into 'cuda-api-wrappers'... git: 'remote-https' is not a git command. See 'git --help'. cloning with the old version of git - works. Why does this happen, and what can I do to resolve it?
Git uses libcurl library to push/fetch repositories via http:// and https://. This error occurs if you compile git without the library present. Install it (yum/dnf install libcurl-devel) and then reconfigure and recompile git. It should work. Link: https://github.com/git/git/blob/b896f729e240d250cf56899e6a0073f6aa469f5d/INSTALL#L141-L149
git clone from https URL fails, says it's 'remote-https' is not a git command and that templates werent' found
1,498,581,374,000
I want to install git on my debian 9 (stretch ) machine , when I type : sudo apt install git-all I get this message : Reading package lists... Done Building dependency tree Reading state information... Done Some `packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The followi`ng information may help to resolve the situation: The following packages have unmet dependencies: git-all : Depends: git (> 1:2.25.0) but it is not going to be installed Depends: git (< 1:2.25.0-.) but it is not going to be installed Depends: git-el but it is not going to be installed Depends: git-cvs but it is not going to be installed Depends: git-mediawiki but it is not going to be installed Depends: git-svn but it is not going to be installed Depends: git-email but it is not going to be installed Depends: git-gui but it is not going to be installed Depends: gitk but it is not going to be installed Depends: gitweb but it is not going to be installed Recommends: git-daemon-run but it is not going to be installed or git-daemon-sysvinit but it is not going to be installed E: Unable to correct problems, you have held broken packages Any help,thank you in advance edit Nothing happends when i type : sudo dpkg --configure -a And the result of this command : sudo apt update && sudo apt upgrade Is this message : Hit:1 http://security.debian.org stretch/updates InRelease Ign:2 http://deb.debian.org/debian stretch InRelease Ign:3 http://httpredir.debian.org/debian stretch InRelease Hit:4 http://ppa.launchpad.net/git-core/ppa/ubuntu focal InRelease Hit:5 http://deb.debian.org/debian stretch-updates InRelease Ign:6 http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 InRelease Hit:7 http://httpredir.debian.org/debian stretch Release Hit:8 http://repository.spotify.com stable InRelease Hit:9 http://deb.debian.org/debian stretch Release Hit:12 http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 Release Hit:13 http://ppa.launchpad.net/webupd8team/java/ubuntu xenial InRelease Hit:16 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease Get:17 https://dl.yarnpkg.com/debian stable InRelease [17.1 kB] Get:18 https://deb.nodesource.com/node_9.x stretch InRelease [4,623 B] Hit:19 http://ppa.launchpad.net/webupd8team/java/ubuntu cosmic InRelease Hit:20 https://repo.skype.com/deb stable InRelease Ign:10 https://get.docker.com/ubuntu docker InRelease Get:21 https://get.docker.com/ubuntu docker Release [1,525 B] Get:22 https://get.docker.com/ubuntu docker Release.gpg [473 B] Ign:22 https://get.docker.com/ubuntu docker Release.gpg Reading package lists... Done W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Translations (main/i18n/Translation-en_US) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11 (main/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11 (main/dep11/Components-all.yml) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11-icons (main/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: GPG error: https://get.docker.com/ubuntu docker Release: The following signatures were invalid: 36A1D7869245C8950F966E92D8576A8BA88D21E9 E: The repository 'http://get.docker.io/ubuntu docker Release' is not signed. N: Updating from such a repository can't be done securely, and is therefore disabled by default. N: See apt-secure(8) manpage for repository creation and user configuration details. W: Target Packages (main/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Packages (main/binary-all/Packages) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Translations (main/i18n/Translation-en_US) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target Translations (main/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11 (main/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11 (main/dep11/Components-all.yml) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1 W: Target DEP-11-icons (main/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list:18 and /etc/apt/sources.list.d/base.list:1
The problem is this: http://ppa.launchpad.net/git-core/ppa/ubuntu focal You can’t use a Ubuntu focal PPA on Debian 9. Remove that from your configuration and you’ll be able to install git. You probably don’t need git-all either, sudo apt install git should be sufficient.
Can't install git on debian9 (stretch)
1,498,581,374,000
I have this in my .zshrc: # command completion autoload -Uz compinit compinit usually letting me tab through commands, args, and files. But with git --git-dir=<the path> --work-tree="$HOME" (usually aliased) it only works for sub-commands (like add and push) and args, not files. I'd like it to work with files too. I tried putting it in a script like so: #!/usr/bin/env sh git --git-dir=<the path> --work-tree="$HOME" "$@" and it works for files but then sub-commands and args break. Thanks.
If --git-dir is present on the command line, the completion code recognizes it and takes it into account when looking for things to complete, if your zsh is recent enough (≥5.3). It does so by passing the argument to --git-dir as the environment variable GIT_DIR. For example, to complete remote names after git fetch, zsh runs git remote. After git --git-dir=/some/where, zsh runs git remote with GIT_DIR=/some/where in the environment. So this part does work. Unfortunately, as of the current zsh version (5.7.1+), it passes the unexpanded argument. So if you write something like git --git-dir=~/repositories/foo.git, zsh passes GIT_DIR=~/repositories/foo.git, not GIT_DIR=/home/aaa/repositories/foo.git. The zsh completion code does not have similar support for --work-tree. I think you can fix the expansion issue with --git-dir and add support for --git-worktree by editing the file _git and replacing the line (( $+opt_args[--git-dir] )) && local -x GIT_DIR=$opt_args[--git-dir] by (( $+opt_args[--git-dir] )) && local -x GIT_DIR=${(e)~opt_args[--git-dir]} (( $+opt_args[--work-tree] )) && local -x GIT_WORKTREE=${(e)~opt_args[--work-tree]} I haven't tested this. I'm not sufficiently motivated to post to the zsh mailing list, but please do: this (or a working version of it, if it doesn't work) would be a useful patch. If you put --git-dir or --work-tree in an alias, this is transparent: zsh expands aliases before doing completion (assuming you haven't turned off the option complete_aliases). If you put them in a function or in a script, this is opaque: zsh won't see them, and won't even know that the function or script calls git unless you tell it. If you can't get this patch to work or you don't want to maintain your own version of _git, you can work around it by defining a custom command with a custom completion function that wraps around git. gitx () { git --git-dir=/some/where --work-tree=/else/where "$@" } _gitx () { local -x GIT_DIR=/some/where GIT_WORKTREE=/else/where _git "$@" } compdef _gitx gitx If you have multiple wrappers, you'll need a completion function for each one. Alternatively, you can add some logic to the completion function to figure out what value of GIT_DIR and GIT_WORKTREE to use. The name of the function is in $service.
Zsh file autocompletion with bare git repo
1,498,581,374,000
The Arch Linux git package installs git-gui under /usr/lib/git-core/. This means git-gui cannot be launched directly from the terminal without specifying the full path: $ git-gui bash: git-gui: command not found $ which git-gui which: no git-gui in (/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl) I'm at a doublt as to what would be the way to properly solve this. Add /usr/lib/git-core/ to system-wide $PATH? Create symlink to /usr/lib/git-core/git-gui under /usr/local/bin? Report a bug in the Arch Linux package? Or upstream? Do nothing - this is not a bug? Thank you.
This is expected behaviour. All git sub-commands are installed to there — you will also find git-commit there, though probably as a link to the main binary for efficiency these days — and the main git command knows where to find them. Any executable git-X there becomes available as git X automatically, and that's the expected way to access them rather than by path or the hyphenated name. git gui is the normal way to access the git-gui executable, and is also what man git-gui will suggest.
How to properly solve "git-gui: command not found" on Arch Linux?
1,498,581,374,000
I'm trying to make an automated backup of my /home directory. In theory this is simple by running this in a cronjob: cd /home git add . git commit -m "nightly backup" git push where push will push the changes to a remote backup server. The problem I have is if there is a git repo in the /home directory e.g. /home/tom/projects/myproject/.git. The backup task runs and pushes all changes to the server. However, any directories that contain repositories are now blank on the server. I realise this could be handled with submodules. However, this has several downsides: Each submodule must be registered with the parent repo (This could be automated but it would be a bit of a pain, recursing into every directory and adding the submodule each time the cron runs) Non-committed changes from the submodule will not be backed up, this is not desirable behaviour for a backup, I want a live snapshot of all the files as they are at the moment, whether or not they're tracked elsewhere I realise there are other tools such as rsync to do this, however it would be nice to have git track the changes over time. Is there any way to have git treat other repositories as if they are just normal files (including their .git directory!) A workaround for this would be running something like this in the cron: Recurse into all subirectories Look for a .git folder Rename .git to something else Then run the standard add/commit/push This will work but will require renaming all the .git folders back during any restoration process. Is there any way to achieve this without this overhead?
I know my comment is not a quite straight answer, but... I would recommend re-organizing your backup methodology in following ways (either / or): Having single "major" repo with all subprojects inside it: one repo for /home I mean. That may look crazy at a first glance, but it depends on complexity of your sub-projects (subdirectories) and may work for something simple and which is not actively developed. Discard your idea and maintain complete backup with special backup solution (rsync is only one of them and not the panacea). That make sense because "why do you need to backup all the git-related stuff?". It's better to look at this as on a higher level of your architecture that needs to be maintained in other way that git (git is something inner). Here I mean that If your main reason of "however it would be nice to have git track the changes over time" is the ability to roll-back the changes to some exact point, then Git is an overhead and not a solution you need. Differential/incremental + full backups with special software (where you can exclude all ".git" folders, btw) is a proper way.
Git Backup /home with other repos inside it
1,498,581,374,000
I am mirroring a Subversion repository tag with svn2git and I want to be sure that when I checkout particular revisions, those I obtain from the git mirror match those from Subversion. My main problem is that subversion tags can be updated, and I need to ensure that checking out the matching tag in the git mirror, matches the equivalent one in the Subversion branch. Are there some tools that can make those checks efficiently? The source is quite a lot with many small files. There are quite a few answers here on the subject involving diff, but I wonder if there are more optimized tools for the job.
diff -qrN is about as fast as it gets to compare two directory trees. The -q option makes it quit early when files differ. Since you expect the files to be identical most of the time, it doesn't matter all that much: the comparison tool has to read and compare the whole files anyway. The only improvement you can make on diff is to avoid checking out from both repositories. Getting git to do the job may be faster then.
What optimized tools are available for comparing directory contents?
1,498,581,374,000
I use git on a regular basis for collaboration with other people. When we work together on a shared repository, I'd like to be able to view the changes performed by others which happened between my last commit and the current master branch (or the current HEAD). Until now I'm using the following workflow: git fetch # download everything git merge # since I'm a trusting person ;) git logadog # my git-alias for `git log --all --decorate --oneline --graph` # manually look into how many commits were performed since my last commit git diff HEAD~3 # if 3 commits were performed since then Alternatively, I could also use git diff c0ffee (if my last commit was c0ffee). Although that works, I'd prefer something simpler, like git diff COMPARE_HEAD_WITH_THE_LAST_COMMIT_FROM_MY_USER, but I'm unsure how that would work. I'm also using the awesome vim-plugin fugitive by Tim Pope and if it would be possible to do this using the :Gdiffsplit HEAD~THE_STUFF_FROM_ABOVE-syntax that would be amazing.
This is not a very 'git like' way to approach the problem. Normally you would just keep a branch which pointed to your last commit. However to answer the question, try the following helper function. This is not going to be very efficient, I probably need to user some lower level commands. my_last_commit(){ local ME="$(git config user.name)" git log --format='%h%n' --author="$ME" -1 } Then you can do git diff $(my_last_commit)..HEAD (omit HEAD if you like as it is the default) or git logadog $(my_last_commit)^..
Display git-diff between master and my last commit
1,498,581,374,000
I have searched the whole universe this error but i could not find any helpful tips. I have created a key using keybase and added my public key to github gpg my gpg --list-secret-keys --keyid-format LONG is this -------------------------------- sec rsa4096/7E8*******60B47B 2021-03-06 [SC] [expires: 2037-03-02] 51FBCD0E******************014D4860B47B uid [ultimate] Fatih <********@live.be> uid [ultimate] Fatih <[email protected]> ssb rsa4096/15BBF8A123C4AC1B 2021-03-06 [E] [expires: 2037-03-02] my .gitconfig is this [user] signingkey = 7E8*******60B47B email = [email protected] name = kgnfth [commit] gpgsign = true [gpg] program = gpg i added export GPG_TTY=$(tty) to my .zshrc file Everytime i run git commit -m "first commit", i get this error error: gpg failed to sign the data fatal: failed to write commit object I dont see anything wrong with the signing key i also tried changing gpg to gpg2 but the same error appears i am out of idea i need your help Thank you.
i resolved my issue by adding gpg-agent plugin to my zshrc config file.
gpg failed to sign the data, failed to write commit object
1,498,581,374,000
What is the proper way to checkout a bunch of .*rc files into a home directory? I've seen lots of github repos online and people usually name them dotfiles, and I guess they get checked out into their home directory; but what I don't understand is... How does one keep their other home files (specific to that machine) separate from their .*rc related files? For instance, you would not want to store /home/<username>/Documents in the dotfiles git repo, but you would want to store .vimrc, /home/vim in the repository. I'm aware of using .gitignore to ignore files for a repository, but I don't want to add an entry to .gitignore every single time I add a file to /home/<username>/Documents. Is there a way to do this the opposite way, that I only specify the files and directories related to my dotfiles project to be included in the repository? Also, if I create a new feature branch for something that I'm already developing, and I check it out, I don't want it to "blow away" the non-dotfiles folders etc when I check it out, or have git complain that the working directory isn't clean before cutting a new branch. Would this somehow require the use of git submodules? What I'd really like to do with this is be able to get on a new Linux box and with the required dependencies installed check out a common version of my .*rc files and related files from my repo, so if I fix it on one, I can just pull the changes to the other machines.
An option is to use symbolic links. For example, say I have my git checkout out in ~/.dotfiles. I might have: .vimrc -> ~/.dotfiles/vimrc .bashrc -> ~/.dotfiles/bashrc .bash_login -> ~/.dotfiles/bash_profile ... I would not, personally, check my home directory itself into the repo.
Proper way to checkout home directory .rc files from a git repo?
1,498,581,374,000
I am trying to make a command for having a nice-looking git log. Say I have the following: git log --color --pretty=format:"%C(cyan)<%an>" --abbrev-commit What I would like to do is to make a variable that takes %an and decides what colour it will be based on the output string. So far, I have USER=$(if [ ! %an = "my own user name" ] then echo "%C(cyan)<%an>" else echo %C(bold blue)<%an> fi) So then I put the variable into the git log such that I have git log --color --pretty=format:"$USER" --abbrev-commit Which should make is so that if a commit has been done by me, it will print my username in cyan; else, it will print the collaborator's username in bold blue. However, it doesn't. I'm just wondering if someone knows what I'm doing wrong here? I suspect it is something to do with printing the variable into an environment that is already a string, but I don't know how to fix it. Any help is appreciated!
You are trying to put a shell script into Git's formatting parameter. Of course, it won't work.1 There are some Git parameters that actually accept shell script, like ones of git filter-branch; but they will be explicitly specified as such in the corresponding manual page. What you are trying to accomplish could actually be done, not by Git, but by using external filter to match names, and mark them up with colors by using ANSI escape sequences. For example, when author name matches with "Joe Average", highlight the name and angle brackets in cyan; otherwise, highlight name and angle brackets in bold blue.2 Leave other parts of the text intact in both cases... Implemented by using Perl 5 as a filter: git log "--pretty=tformat:%h <%an> %s" | perl -n -e ' chomp; if(/^(.*)<([^>]*)>(.*)$/) { if ($2 eq "Joe Average") { print $1."\e[36m<".$2.">\e[39m".$3."\n"; } else { print $1."\e[1m\e[34m<".$2.">\e[39m\e[0m$3\n"; } } else { print $_."\n"; }' Implemented by using sed as a filter (a bit hacky3)... git log "--pretty=tformat:%h <%an> %s" | sed ' s/<\(Joe Average\)>/\x1B[36m<\1>\x1B[39m/g; t matched; s/<\([^>]*\)>/\x1B[1m\x1B[34m<\1>\x1B[39m\x1B[0m/g; :matched' Regular output (without filter) from a test repository: $ git log "--pretty=tformat:%h <%an> %s" e7f3209 <Joe Average> improving portability e3ebe74 <Jim Sixpack> adding first working prototype Highlighted output (passed through either filter): Note that these filter commands would still work even when you changed the format of git log output, provided that: Author name is always enclosed in < >. There's no more than one author in a single line. There's no other thing getting enclosed in < >. A different way to do what you asked is doing two different git log call with different --author and --pretty, merge results together, and sort them by timestamp; but the tricky part is making sure that output of both git log calls don't give overlapping output. (You can't use uniq since doing this marks both of them with different escape sequences) Footnotes 1 Actually, due to a lack of quoting, your if [ ! %an = "my own user name" ] ... would be already be executed at the USER= line (%an will be compared literally— it doesn't have special meaning in shell); making it effectively USER="%C(cyan)<%an>" before you could even invoke git log command. 2 Also, you said you would like to highlight your own name in cyan, and others bolded in blue; but your original code actually tried the reverse: if (author name) is not (my own user name), highlight in cyan, else highlight in bold blue. I'm sticking to your description. 3 \x is an extension of GNU sed, your mileage may vary if you are using this on non-GNU system.
Echoing from a variable in a specific part of a string
1,498,581,374,000
This is completely theoretical, but I'm new to Git and Linux so I want to know. If I accidentally manage to do git init inside e.g Desktop or Home directory, how to prevent any possible disaster from happening? git init creates hidden .git directory where it's config-files are so is it just so simple to remove this hidden directory? Would the directory it was in become "normal" again instead of git master branch? Or would removing .git cause some problems? Like the directory trying to identify itself as git repository but cannot find the configs?
If you run git init in a directory which isn’t already a git repository, removing .git will reverse all the effects of git init without any other side-effects.
Git init in wrong directory? How to recover? (theoretical situation)
1,498,581,374,000
Using source-highlight in conjunction with less works really well, but I'm struggling to see how I can use it with git show because there's no file extension to clue source-highlight about the language used in the git output... less somefile.rb # result is syntax colourised git show master:somefile.rb | less # no colouring Using calling git show master:somefile.rb | less is effectively the same as calling less somefile (ie no .rb); because there's no extension, there's no way for source-highlight to guess the syntax. Is there a non-extension way for source-highlight to guess, or can I pass a --lang-def option into the LESSOPEN variable somehow? Edit 1 Ah, so it looks like source-highlight can use other methods to infer the language but I don't have any of those in my source files.
I ended up modifying gnu source-highlight's src-hilite-lesspipe.sh so it could work with piped files: https://gist.github.com/jaygooby/9494858d3d481a64819d227a9318f6c7 This means that as well invoking in a regular fashion: less code.py You can also get source highlighting for extensionless files that don't have any of the language inference features that source-highlight uses: less /tmp/mycode And (the original motivation for doing this) piped files: cat /tmp/file.rb | less git show master:obfusicated.perl # implicit pipe to less via git's pager If you know your code uses a syntax that source-highlight doesn't have any definition files for, you can override the guess, by setting a similar language. c is often a good fallback: SRCLANG=c git show master:app/views/layouts/application.html.erb Here's a raw copy of the gist that lives at: https://gist.github.com/jaygooby/9494858d3d481a64819d227a9318f6c7 #! /bin/bash # # Based on http://git.savannah.gnu.org/cgit/src-highlite.git/tree/src/src-hilite-lesspipe.sh.in # by Lorenzo Bettini # # Modified by Jay Caines-Gooby to support piped files # [email protected] # @jaygooby # # Typically called by setting: # # export LESSOPEN="|-/path/to/src-hilite-lesspipe.sh %s" # export LESS=-R # # If we're less-ing a file, %s will be replaced by the name of the file. If # there's no file and we're reading from a pipe, then %s is set to - # # This script differs from the original src-hilite-lesspipe.sh # in that it can handle pipes and files with no extensions and will # attempt to guess their language using the file command. # # So as well as invoking on regular files: # # less some.rb # less some.py # # It will should be able to work on: # # less no-extension-but-contains-perl # # and even with more complex examples (my original motivation # https://unix.stackexchange.com/questions/469982/how-can-i-use-source-highlight-with-git-show) # # git show master:some.rb # # It uses bashisms to do this, so is no longer a pure POSIX sh script. set -eu # Users can override the guessed language by setting SRCLANG: # SRCLANG=c git show master:app/views/layouts/application.html.erb SRCLANG=${SRCLANG:-} guess_language() { lang=$(echo -e ${1:-} | file - | cut -d" " -f2) echo $(tr [A-Z] [a-z] <<< "$lang") } # check if the language passed as $1 is known to source-highlight # In an earlier version of this script I set a fallback (c.lang) # but this causes issues with paging man pages etc check_language_is_known() { fallback="" lang=$(source-highlight --lang-list | cut -d' ' -f1 | grep "${1:-}" || true) lang=${lang:-$fallback} echo $lang } for source in "$@"; do case $source in *ChangeLog|*changelog) source-highlight --failsafe -f esc --lang-def=changelog.lang --style-file=esc.style -i "$source" ;; *Makefile|*makefile) source-highlight --failsafe -f esc --lang-def=makefile.lang --style-file=esc.style -i "$source" ;; *.tar|*.tgz|*.gz|*.bz2|*.xz) lesspipe "$source" ;; *) # naive check for a file extension; let source-highlight infer language # but only when source isn't - (ie. from a piped file) if [[ "$source" != "-" && $(basename "$source") =~ \. ]]; then source-highlight --failsafe --infer-lang -f esc --style-file=esc.style -i "$source" else # We're being piped to, or the filename doesn't have an extension # so guess the language. # When we're being piped to, we cat stdin, but when it's a file # without an extension, we cat the file instead. # unset IFS so line breaks are preserved and capture the file's contents # (will only work for files up to bash's available memory). There should # be a better way to replicate this with tee or process substitution... IFS= file=$([ "source" = "-" ] && cat || cat "$source") lang=$(guess_language $file) lang=$(check_language_is_known $lang) # Don't call if source-highlight doesn't know the language # BUT also let users override the guessed lang if the environment # variable SRCLANG is set. This can help where you know e.g. your # source code is c-like, but source-highlight has no specific syntax # definition for your code [ -n "$SRCLANG" ] && lang="$SRCLANG" if [ -n "$lang" ]; then echo $file | source-highlight --failsafe -f esc --src-lang=$lang --style-file=esc.style else echo $file fi fi ;; esac done
How can I use "source-highlight" with "git show"?
1,498,581,374,000
I need to insert user credentials into an HTTP string so I can properly populate my git credentials file at ~/.git-credentials. These are the three environment variables I have to start with: user="someUser" pass="somePass" uri="http://sometld.org/path/repo.git" I've been fiddling with awk, but it will only work with Github style cloning paths (https://github.com/org/repo.git) and won't work with non-standard paths (https://git.private.org/scm/~user/path/repo.git): proto=$(echo $uri | awk -F"/" '{print $1}') domain=$(echo $uri | awk -F"/" '{print $3}') repo_path=$(echo $uri | awk -F"/" '{print $4}') repo_name=$(echo $uri | awk -F"/" '{print $5}') echo "$proto//$user:$pass@$domain/$repo_path/$repo_name" # http://someUser:[email protected]/path/repo.git What is the best/easiest way to insert a username and password into an HTTP string so I can populate my ~/.git-credentials file?
$ sed -e "s^//^//$user:$pass@^" <<<$uri http://someUser:[email protected]/path/repo.git This replaces // with //$user:$pass@ in the string $uri and will work anywhere. In Bash specifically: $ echo ${uri/\/\////$user:$pass@} http://someUser:[email protected]/path/repo.git will perform the same replacement - this is just ${variable/pattern/replacement}, but it's necessary to escape the slashes in the pattern because we can't change the delimiters here.
Insert credentials into HTTP string?
1,498,581,374,000
possible duplicate : watch command not showing colors for 'git status' running the following command: watch -n1 git --no-pager log --oneline --graph -20 reproduces what i expect only it strips colors. In the possible duplicate it says that git detects that stdout is not terminal and hence strips the colors but the solutions does not work for git log on my machine (osx high sierra, zsh) note - the following code does give me the everything with colors - i'm just interested if watch can do it too: while : do clear date git --no-pager log --one-line --graph --20 sleep 1 done
Rather than always forcing git to color, you can enable color for just one command with a flag: git log --color So your command would be: watch --color -n1 git --no-pager log --color --oneline --graph -20 I'm not sure why the linked answer didn't work, but I hope this works better.
why does watch remove the colors from git log
1,498,581,374,000
I used cp -uav to update a copy of a git repo, including uncommitted files. Why did it say it's removing files? It looks like this: $ cp -uav repos copy removed 'copy/repos/h/.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391' removed 'copy/repos/h/.git/objects/3b/b3f834dd037db9298b10d71e0cd7383000fa1c' removed 'copy/repos/h/.git/objects/49/6d6428b9cf92981dc9495211e6e1120fb6f2ba' removed 'copy/repos/h/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885' $ rpm -q --whatprovides `which cp` coreutils-8.25-17.fc25.x86_64
I can reproduce the above messages as follows: mkdir test; cd test mkdir repos; cd repos mkdir g; cd g git init touch a git add a git commit -m test cd .. git clone g h cd .. mkdir copy cp -ua repos copy cp -uav repos copy The running the cp -ua command under strace will show that it is indeed removing (unlink) the files it says. What's happened is that the objects in repo/h/.git/objects are hardlinks of the ones in repo/g/.git/objects. (In my original case, I was copying a repo which contained sub-repos, which were originally created as clones of the main repo). cp -a means cp --preserve, which is documented as --preserve[=ATTR_LIST] preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all The unlink happens as part of hardlink preservation: linkat(AT_FDCWD, "copy/repos/g/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885", AT_FDCWD, "copy/repos/h/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885", 0) = -1 EEXIST (File exists) unlink("copy/repos/h/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885") = 0 linkat(AT_FDCWD, "copy/repos/g/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885", AT_FDCWD, "copy/repos/h/.git/objects/2b/bf350cea1fb4fd036235d7e6c36eb600e68885", 0) = 0 As to exactly why it generates messages which confused me so? It seems like -u (--update) is not quite implemented in this code. It's mainly a performance optimization to avoid re-copying data unecessarily. Making hardlinks doesn't require copying any data. We can see other scenarios in the documentation where cp must remove files as well: -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) In the case of -f, I can understand that it might want to show the specific files that it has to "force". I suppose it might also be useful to show deletion, in case cp is interrupted. Otherwise, users would be unlikely to realize that a file could have been deleted from the destination (as an intermediate step). The ultimate question is why it did not also show a message when it re-created the links, which would be less confusing. I suspect this is a quirk of the -u option.
Why did `cp -uav` of a git repo show "removed" for some files?
1,498,581,374,000
I'm learning about SHA1 (specifically wrt Git), and I wanted to sanity-check my understanding by calculating a string's SHA1 with different methods - I expected identical SHA1 hashes, but instead I got distinct results from three of four methods: >git hash-object --stdin <<< "Apple Pie" 23991897e13e47ed0adb91a0082c31c82fe0cbe5 . >sha1sum <<< "blob 9\0Apple Pie" 332cd56150dc8b954c0b859bd4aa6092beafa00f - . >printf 'blob 9\0Apple Pie' > foo.txt >sha1sum foo.txt 9eed377bbdeb4aa5d14f8df9cd50fed042f41023 foo.txt . >openssl sha1 foo.txt SHA1(foo.txt)= 9eed377bbdeb4aa5d14f8df9cd50fed042f41023 The accepted answer to this Stack Overflow question says that git hash-object runs a SHA1 hash on the specified content prefixed with "blob [file size]/0". Thus I explicitly prefixed that text to the strings I tested with the non-git method. Why all these different results? I thought SHA1 was a specific and unique hash of a given string, and that there were not different "types" of SHA1 - is that not true?
The differences don't come from SHA1, but the input. The here-string syntax appends a newline, as we can see with od: $ od -c <<< foo 0000000 f o o \n So in your git command the input is the ten characters Apple Pie\n. In addition, the double quotes you used in the here-strings don't support backslash escapes like \n or \nnn, so <<< "blob 9\0Apple Pie" gives a string containing a literal backslash and a zero. printf however does interpret \0 as the NUL byte, and it doesn't add a trailing newline, so with the newline added and the length fixed, we should get the expected output: $ printf 'blob 10\0Apple Pie\n' | sha1sum 23991897e13e47ed0adb91a0082c31c82fe0cbe5 - We could try to do the same with the here-string using the $'' quote which does support \0 as representing the NUL byte, but that may not work in all shells, since the NUL byte ends the string. E.g. Bash cannot deal with it, zsh can: $ zsh -c "sha1sum <<< $'blob 10\0Apple Pie'" 23991897e13e47ed0adb91a0082c31c82fe0cbe5 -
Different methods to get SHA1 give different results
1,498,581,374,000
I have a bash script that I've written during the course of the last week. Today, I've decided to finally give git a try before making any further changes, created a git repository, etc. The script has two versions: script.sh and script1.sh. My question is whether there is a way to tell git that the latter is an updated version of the former? I've read the beginner chapters of the "git book" about 3 or 4 times now and I'm a little shaky on terminology, still. I don't think that merge is what I'm looking for. I've committed both of the files, but from what I understand that just means that they are two separate files of a project to be tracked. From now on I'll just be editing one file with its changes tracked, but is there a way to neatly preserve my work in the version control system from the "pre-git" days? Or am I imagining a function that isn't there?
Yes, you overwrite script.sh with script1.sh, after an initial commit. Starting from scratch: git init git add script.sh git commit -m "First version of script.sh" mv script1.sh script.sh git add script.sh git commit -m "Second version of script.sh" You'll then be able to see both versions of script.sh in git log, check out the previous version etc.
git: how to add one file as a version of another?
1,498,581,374,000
I just recently installed gitg and whenever I tried to make a commit, I encountered an error of missing author details. However, I am unable to change author details as no editing window pops up after I clicked on the the author details tab...
To get rid of the error you need to set your user name and email address. There are two main contexts where you will likely want to set this Specific to your user account i.e. ~/.gitconfig This setting will apply to any git project belonging to your user account On a project specific basis i.e. in <your_git_project>/.git/config This setting will be used by that particular project - if for some reason you want a particular project to attach a different username and email address to your commits. You also can set config options at a system wide level - but I'm not going to cover that to set an email address at a user level git config --global user.name "John Doe" git config --global user.email [email protected] to set an email address at a project level. cd in to the root of the git repo git config user.name "John Doe" git config user.email [email protected]
how to edit author details for gitg?
1,498,581,374,000
I need to let untrusted users, strangers, upload their id_rsa.pub to my server and onto a given user's authorized_keys (user git in my case). What is the safest way of achieving that, without having to do anything manually? I am particularily thinking about a web interface, but if there are strong advantages of another method, I am open to ideas. The http daemon runs as user http, and git must not be vulnerable to attacks from the http user, in case http gets compromised.
Use another processes as a middle-man. Your web service (or whatever) writes new requests to a spool somewhere. The middle-man watches the spool, removes and sanity checks new entries, and append what's valid to git's authorized_keys file. The same middle-man can give feedback that the web service can read. But a compromised http user cannot manipulate the middle-man or the git user. Your middle-man can be a daemon or even a cron job. Alternatively, since you're obviously into bad ideas :), we can take advantage of the fact that 1), no matter what, the git user will have write access to its own authorized_keys file and 2) you're ok with literally anyone having SSH access to the git user. So, since your http user falls under "anyone", give your http user an ssh key-pair and add the public key to the git user's authorized keys file. Now, your web service can simply do an ssh -n git@localhost echo $key >> ~/.ssh/authorized_keys. There's no lapse in security here, because a stranger with SSH access would be able to do exactly this anyway. If getting a shell isn't something that you want to be possible for your open-access git user (because security is important, you know), but if you'll still allow git push to be issued over SSH, then you can get really meta by creating a repository just for public key commits. Your http user will have a clone of this repository and your web service will issue commits and pushes. Then, a server-side hook can sanity check the key(s) in the commit and add it to the authorized_keys file of your git user upon validation. But let's assume that this all gets completed somehow in some fashion. What you'll have is a system where anyone can grant themselves SSH access for your git user. So then what's the point of SSH authentication at all? Do you want strangers to have shell access? Why not just null the git user's password and allow empty passwords? Or, if you don't intend on these users having anything but the ability to clone over SSH, then why not avoid this entire mess by just serving your repositories over http or the git protocol?
Safe way of letting users upload their public keys
1,498,581,374,000
I want to run the following commands: git diff git commit git commit will open the default editor to edit the commit message. But if the difference if not too long it will close immediately. How can I prevent closing git diff before pressing Enter or other keys?
git uses less as a pager. If you want to use the pager on a specific, just pipe the output directly to less (git won't try to invoke less itself if it is outputting to a pipe, so no need to worry about have two less processes). Just do: git diff | less You could also add similar options to less that git does to get the same output, and add the --color option to git diff to get colour: git diff --color | less -RSX
git diff - listen for key press
1,498,581,374,000
How can I get total size of Git LFS files? I can get a listing of LFS files with git lfs ls-files --size: b1d5dd29dd - file1.zip (1.42 GB) 27d3073f43 - file2.zip (120 MB) cacd6dbfe3 - folder/file3.zip (110.2 MB) 295442cd34 - "folder/(120 MB).zip" (110.2 MB) 680bb2ab19 * test.txt (5 B) Note: both - and * are used. I can filter to get only the sizes using git lfs ls-files --size | awk -F " " '{ print $(NF-1) $NF }' | tr -d '()': 1.42GB 120MB 110.2MB 110.2MB 5B I don't know if these are powers of 1000 (GB) or 1024 (GiB), so it is fine to assume the larger one (1.00 GB = 1024 MB). How can I get the total of 1.88 GiB ((1.42) * 1024^3 + (120 + 110.2 + 110.2) * 1024^2 + (5) * 1 = 1881648665.48 bytes = 1.88 GiB)? An alternative way of getting total size without parsing the Git equivalent of ls is also acceptable, preferably using plain Bash and GNU tools.
I can't find any option specifically to print sizes in bytes rather than human readable sizes however it looks like the --debug option does this. The output of --debug is quite different though and according to the man page "the exact format may change at any time" so keep that in mind. However with the sizes in bytes we can do something like this: git lfs ls-files --debug | awk -F: '$1~/size/{t+=$2}END{printf "Total is: %dGB\n", t/1024/1024/1024}' Here awk will sum up every value of "size" in the t variable and after reading all lines it will print out the value of t/1024/1024/1024 or GB, add another /1024 for TB or remove one for MB, etc. (Note I do not recognize the existence of "metric" data sizes and therefore do not recognize "GiB", "MiB", etc)
Get total Git LFS size
1,498,581,374,000
As background, I'm using git on an hp-ux 11.11 (11v1) system. I'm doing an extensive .gitignore file to exclude many many files. My .gitignore is basically "Ignore everything, except these directories, but also ignore these patterns under those directories." Precisely how and why is not exactly relevant to the question. My object is to be sure I'm getting what I expect to get when I run git add before running git add. To accomplish this, I'm running tests against a given directory's files with git check-ignore. My approach normally looks thus: find test2 -type f -exec git check-ignore -v -n {} \; grep ! For clarity, the repository exists in the root (/.git) (it's actually symlinked to /baz/dev/myRepo/.git), so I'm calling, for example, git status from /. I'm also calling find from / so that the paths match what git is expecting to see and the format of the paths returned by find to the -exec action match. Standard output for this would look something like the following: .gitignore:208:!test2/backupScripts/** test2/backupScripts/CV_PostJob.sh .gitignore:208:!test2/backupScripts/** test2/backupScripts/CV_PostJob.sh.old .gitignore:208:!test2/backupScripts/** test2/backupScripts/CV_PreJob.sh .gitignore:208:!test2/backupScripts/** test2/backupScripts/CV_PreJob.sh.old .gitignore:208:!test2/backupScripts/** test2/backupScripts/CV_ScanCheck.sh .gitignore:208:!test2/backupScripts/** test2/backupScripts/oldCH.txt .gitignore:212:!test2/scripts/** test2/scripts/deprecated/CommvaultBackupScript.sh .gitignore:212:!test2/scripts/** test2/scripts/deprecated/NetBackupScript.sh .gitignore:212:!test2/scripts/** test2/scripts/benchmark.sh .gitignore:212:!test2/scripts/** test2/scripts/migrateVolumeSync.sh .gitignore:212:!test2/scripts/** test2/scripts/test.sh .gitignore:206:!test2/* test2/CommvaultBackupScript.sh .gitignore:206:!test2/* test2/NetBackupScript.sh .gitignore:206:!test2/* test2/benchmark.sh .gitignore:206:!test2/* test2/test.sh Generally, this technique works well, however there are in some cases directories such as /test2/foo and /test2/bar which both contain large numbers of files which will be excluded by patterns in the .gitignore: #Ignore everything * #add back /test2 !test2 !test2/** #reignore foo and bar test2/foo test2/bar So, the core problem is: I'd like to be able to run find test2 -exec git check-ignore without enumerating test2/foo and test2/bar and not have to write a command like find test2 -name foo -prune -o -name bar -prune -o -type f -exec git check-ignore {} \; especially for cases where the ignored subdirectories may number over a dozen and in reality, I just want to validate that the files immediately in test2/ specifically are going to be properly included, and then do another run to validate a single small subdirectory such as test2/backupScripts. Ultimately, I'd like to adapt the POSIX compliant command find . -type f -print -o -name . -o -prune such that it can be run with -exec and so that find passes paths to git check-ignore which are absolute instead of relative. However, I'm at a loss understanding how exactly that command works. I can confirm that it does indeed only scan the root directory of wherever it is run from. I'm laboring under the restriction of not having a modern version of findutils, and no apparent availability of GNU findutils for the platform, so -maxdepth option is not available. Additionally, /test2 is a mountpoint, so running git from within test2 for the repository at /.git will require modifying Git's environment (export GIT_DISCOVERY_ACROSS_FILESYSTEM=1) to enable traversing mountpoint boundaries (at which point cd test2 && find . -type f -exec git check-ignore --no-index -v -n {} \; -o -name . -o -prune | grep ! works fine). I'd prefer not to do this if it's possible (for other uses of Git on the system). So, how exactly does find . -type f -print -o -name . -o -prune work? Can it be modified to replace one or more of the dots with some pathspec that will enable it to be called from /? Or is this some kind of "magic" (as in: the desired behavior can only be elicited when options are provided in this order) sequence that performs a specific function when provided in this specific order? A google search for this specific command appears to return little else besides reposts of this specific answer itself in multiple languages: find without recursion I've attempted to deconstruct this specific command's behavior by doing the following: cd / find test2 -type f -print -o -name . -o prune #no output cd /test2 find . -type f -print -o -name . -o -prune #get files in CWD as expected find . -type f -print #gives me all files and directories below this, as you would expect find . -type f -print -o -name . #gives the same as the prior command find . -name . #gives just the CWD entry (.) find . -name . -o -prune #gives just the files and folders in CWD, including the (.) entry cd / find test2 -name test2 -o -prune #also gives the files and folders directly in test2, including test2 itself find test2 -name test2 -o -prune -o -type f -print #no output find test2 -name test2 -prune #returns just test2 itself find test2 -type f -print -o -name test2 -prune #predictably gives no output, as test2 is pruned find test2 -type f -print -o -name foo -prune #gives full directory list except for /test2/foo, as expected. find test2 -type f -print -o -name "test2/*" -prune #gives full directory list, as a / will never be in the "base" name which find tests. cd / find test2/* -type f -print -o -prune #this is the closest, same as "find . -name . -o -prune" but with cd to test2 first.
find . -type f -print -o -name . -o -prune Is a more convoluted way to find regular files in the current directory and not in subdirectories than the more canonical: find . ! -name . -prune -type f Which with the GNU implementation of find (or those which have copied GNU find's -mindepth/-maxdepth) can also be written: find . -mindepth 1 -maxdepth 1 -type f (-mindepth being redundant in this case as -type f would exclude . (depth 0) anyway). In: find . -type f -print -o -name . -o -prune . is the file which find will start searching for files with. . itself is not a regular file so it won't be printed, and the right part of the first -o will be tested. -name . matches, so the expression resolves to true and the -prune is not run. Because the whole find expression includes a -print which is an action predicate, there is no implicit printing even though the expression as a whole resolves to true for that file. Now, since . was not pruned, and since it's a directory, find will read its contents and apply the expression to each of the files in it (to the exclusion of the . and .. special entries). For those, for files of type regular, -print will be run. For any other type of file, since -name . cannot match, -prune will be executed. And for those files that are of type directory, that means that find won't descend into them. So the important things in there are: regular (f type) files are printed directories other than . (the top level one) are pruned, so find won't descend into subdirectories.
How does find . -type f -print -o -name . -o -prune actually work?
1,498,581,374,000
Basically i have a automated building script where i do a checkout of a local branch, and want to step to pull remote updates with git pull && git submodule update && make clean only if necessary, because otherwise i'd be wasting a lot of time when it was time to build. I noticed that if had a local change going on and there are remote updates, or just remote updates, the output of git checkout in both cases would have a substring 'Your branch' (can be fast forwarded, or something similar), so i hacked that as my condition. I'm uneasy about this. Is there a reliable way to check that the remote has updates to pull and that can pulled without merge conflicts? edit: what i currently have, inside a larger script is this: OUTPUT=$( { git checkout "$NAME" ; } 2>&1 ) || { echo "Failed checking out branch" >&2; exit 1; } [[ "$OUTPUT" == *"Your branch "* ]] && { git pull && git submodule update && make clean || { echo "Failed pulling, updating or cleaning branch" >&2; exit 1; }; }
You are going to need to get the information from the remote repo at some stage. At the moment you are using git pull to download the information and merge it. You should split this into 2 steps, first download the information of the state of the remote repo. As a second step see if you are up-to-date, if not then merge the data, do your make clean and make. As git pull --help tells you, it runs git fetch and then either git rebase or git merge. If you know the name of the local branch and the branch it is tracking, then you can use the low level command git show-ref to get the hash values and see if they are equal. This only works if you are exactly tracking an upstream branch but is very cheap. same_commit(){ set -- $(git show-ref --hash --verify "$@") [ "$1" = "$2" ] } # get the changes if any, but don't merge them yet git fetch origin # See if there are any changes if same_commit mainline origin/mainline then echo "Everything up to date" exit 0 fi # Now merge the remote changes git pull origin make clean make If you have local changes as well then you need to see if your local branch has all of upstream. contains(){ # return true if the first name has the second as an ancestor git merge-base --is-ancestor "$2" "$1" } if contains master origin/master then echo nothing to do return 0 fi
Is there a better way than string output hacks to check git checkout needs a pull to update?
1,498,581,374,000
I'm trying to extract the name of the folder created by git. The output says: ... Cloning into 'repository-name'... ... I want to pipe this output into grep to extract the one line that says Cloning into 'repository-name'. However, when I run git clone https://github.com/username/repository-name.git | grep "Cloning into", git appears to bypass grep and print output directly to the screen, since I get the full git output message with no grep highlighting. Sending the --no-pager flag to git doesn't help.
From git-clone man page: --progress Progress status is reported on the standard error stream by default when it is attached to a terminal, unless --quiet is specified. This flag forces progress status even if the standard error stream is not directed to a terminal. So we have to do Redirecting of Standard Descriptors as git-clone outputs on the standard error stream. This will probably do git clone https://github.com/username/repository-name.git --progress 2>&1 | grep "Cloning into"
How do I grep output from git?
1,498,581,374,000
I occasionally encounter such an error: $ which bash /usr/local/bin/bash bash: prompt_git: command not found The report is obscure, since I did not manipulate git. When it's rebooted, the error disappear. However, it will abruptly emerge after some uncertain operations were executed.
The problem you are having is caused by a bad setting in your .bash_profile/.bashrc file. One of the shell variables PS1 or PROMPT_COMMAND contains a call to prompt_git which is not (at that point) in your PATH. PS1 defines the prompt you see in the terminal and PROMPT_COMMAND is run every time the prompt is displayed.
error `bash: prompt_git` report when no git operations performed
1,498,581,374,000
On Cygwin, running git clone git@..., git pull or git push, where the remote is an SSH repository address, fails. Below is output of running git clone: Cloning into 'iko-app-rocket'... fatal: cannot run C:\Users\sakynimoD\scoop\apps\openssh\current\bin\ssh.exe: No such file or directory fatal: unable to fork As you can see from the path, I had used scoop, the Windows package manager. I used it to install Gradle, and it installed some other things as dependencies, including ssh. I've since deinstalled scoop, in the recommended way, along with all the packages it installed, but the error persists. A workaround is declaring that git should use the ssh executable for SSH, which sounds rendundant, but apparently isn't: env GIT_SSH=ssh git pull works.
Since you discovered that explicitly setting GIT_SSH=ssh works, the next thing to investigate is if it was already set, possibly by scoop. You can check by running echo "$GIT_SSH" or alternatively by running env to display the entire environment. If it is set, that could either be coming from Windows' environment variable settings or from a .bashrc or similar.
Git functions requiring SSH broken on Cygwin
1,498,581,374,000
How can I modified this script to conditionally execute ${deleteOldBranchRemote} when there is no error executing ${getRename}? Now_hourly=$(date +%d%b%H%M) #echo "$Now_hourly" newrcName="rc$Now_hourly" #rename rc to the new name getRename="git branch -m $newrcName" #Delete the old-name remote branch deleteOldBranchRemote="git push origin --delete rc" ${getRename} #if getRename has error then do not execute the following line #if [ $noErrorSomehowIneedToCheckForErrors ] #then ${deleteOldBranchRemote} #fi
You can write it like this: if git branch -m $newrcName; then git push origin --delete rc fi So the second command is only executed when the first command finishes with an exit code of 0 which indicates success. You can get more info about the if keyword by running help if. Example output from my system (Bash 4.3.46(1)-release): if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi Execute commands based on conditional. The `if COMMANDS' list is executed. If its exit status is zero, then the `then COMMANDS' list is executed. Otherwise, each `elif COMMANDS' list is executed in turn, and if its exit status is zero, the corresponding `then COMMANDS' list is executed and the if command completes. Otherwise, the `else COMMANDS' list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true. Exit Status: Returns the status of the last command executed. If you want to know the error code you can read it from $?. Bash stores the exit code of the last executed command in this variable. You can store it in a variable to use it later: git branch -m $newrcName BRANCH_EXIT_CODE=$? echo "git branch -m $newrcName exit code was $BRANCH_EXIT_CODE" # $? now contains the exit code of the preceding echo if [ $BRANCH_EXIT_CODE -eq 0 ]; then git push origin --delete rc fi
Checking for errors in bash script
1,498,581,374,000
Suppose we have a directory with a git repository & files: .git /test/inside-1.txt /test/outside-1.txt outside.txt inside.txt "inside" files are within git repository, "outside" are not. I'd like to know, how to get the files, that are outside repository and inside. I know, how to get "inside": I need to run git ls-files, it outputs: test/inside-1.txt inside.txt How to get the "outside" files in the same format? test/outside-1.txt outside.txt
Maybe you can try with git ls-files --others --exclude-standard. This should list files which are not defined in .gitignore.
How to find out which files are outside git repository
1,498,581,374,000
I basically want to find all git repos that have neither a .gitattributes nor a .gitignore file at the root. I used find . -type d '!' -exec test -e "{}/.gitignore" ';' -print to find it but it lists out all the directories instead of only the top level git directories. My directory tree looks like this: GitHub ├─ _Clones | ├─ repo1 (has .gitignore) | └─ repo2 ├─ _Forks | ├─ repo1 (has .gitattributes) | └─ _For-Later | ├─ repo2 | └─ repo3 ├─ myrepo1 (has both) ├─ myrepo2 (has both) ... └─ myrepo10 In such a layout I would want the output to be _Clones\repo2, _Forks\_For-Later\repo2, _Forks\_For-Later\repo3 and myrepo10. I've tried using depth parameter for find but that is a variable for each directory!
To list the root directories of git repositories, I use the following: find . -name .git -print0 | xargs -0 dirname A variant finds all folders containing .gitignore: find . -name .gitignore -print0 | xargs -0 dirname Determining git repositories whose root doesn't contain .gitignore is then simply a set operation on the two sets of folders: comm -23 <(find . -name .git -print0 | xargs -0 dirname | sort) <(find . -name .gitignore -print0 | xargs -0 dirname | sort) This compares the two sets of folders (which have to be sorted) and lists those which only appear in the first set. The <() operation is process substitution and allows the output of any command to be used as input to another command instead of a file. Replace .gitignore with .gitattributes above to find the git repositories which don't contain .gitattributes in their root directory... To get the final output you're after, combine both: comm -23 <(comm -23 <(find . -name .git -print0 | xargs -0 dirname | sort) <(find . -name .gitignore -print0 | xargs -0 dirname | sort)) <(find . -name .gitattributes -print0 | xargs -0 dirname | sort)
Find all git repos that do not contain any one of .gitignore and .gitattributes
1,498,581,374,000
dir1 has 1 file and dir2 has 2 files as below: /tmp$ ls dir1 file1 /tmp$ cat dir1/file1 line1 line2 line3 /tmp$ ls dir2 file1 file2 /tmp$ cat dir2/file1 line1 /tmp$ cat dir2/file2 line1 /tmp$ diff -ur dir1 dir2 | diffstat file1 | 2 -- file2 |only 2 files changed, 2 deletions(-) I am looking for a command to print the lines in dir2 new files as insertions(+) dir2/file2 has one line, so I am looking to print 2 files changed, 2 deletions(-), 1 insertions(+) This question is relevant to Diff of directory statistics sumarry (git diff --stat like for non-git repo) Thanks!
You need to use the -N (treat missing files as empty) option to diff. For example: $ diff -N -u -r dir1/ dir2/ | diffstat file1 | 2 -- file2 | 1 + 2 files changed, 1 insertion(+), 2 deletions(-)
git --diff like command for Linux local dirs
1,498,581,374,000
So I have a python script that pulls down git/svn/p4 repositories and does some writing to a database. I'm simply trying to automate the running of this script and based from what I see in syslog it is being run, even the file I tried piping the output to is being created however the file is empty. Here is the cron job: 10 04 * * * user /usr/bin/python2.7 /home/user/script.py -f someFlag > ~/cronout.log 2&>1 Kinda stumped and don't know where to start. Thinking its maybe the requirement of passwords for the keychain and what not. Any ideas would be helpful!
So it turns out the problem was with environment variables that the Python script needed, and it was so early on in the script that it broke the script before it even output anything. Cron does not have a regular environment. Furthermore ssh passwords were required for pulling git repos which i was able to solve by using Keychain. Using the help of this blog post and some bash wrapper scripts I was able to get everything working and automated.
Cron job not behaving as expected
1,498,581,374,000
I've started working with a git repository that includes a large amount of content that should be assumed readonly. So, every time I throw a new branch: git checkout -b newBranch it should be followed by the command git update-index --assume-unchanged LARGE_READONLY_DIRECTORY I figured this would be a perfect opportunity to try my fledgling bash skills, so that all I need to do at the shell is the first line, and it would execute that, then the second, without me remembering to do it (which I won't). I figured what I want to do is have a function in my .bashrc that checks whether the first argument is 'checkout', and the second it '-b'. That first check is easy, but I can't figure out how to note the presence of -b. git() { if [[ $1 == 'checkout' ]] && [[$2 == '-b']]; then echo 'yep!'; fi; command git "$@"; } When I execute this, it complains that [[-b: command not found. Presumably the fact that it's an option, rather than an argument, is important here. Can anyone tell me how to check for the presence of that argument, so I know to execute the follow-up command?
You need a space between [[ and $2. For bash [[ is not syntax, it is a builtin command (or keyword to be precise). Bash will execute [[ with all its parameters, including the closing ]]. When you have no space between [[ and $2 bash will not see the keyword [[, instead it will see this thing: [[-b (after expanding $2 to -b). Bash will then try to execute the string [[-b as a command and fail. See help [[ for more information. For the same reason you also need a space before the closing ]]. Here is your code fixed: git() { if [[ $1 == 'checkout' ]] && [[ $2 == '-b' ]]; then echo 'yep!'; fi; command git "$@"; } See also the bash pitfalls and the bash FAQ. IMO the best way to learn bash scripting... or the best way to learn not to do too much bash scripting.
How to extend a command in bash so that it expands based on options?
1,498,581,374,000
I have found a patch applicable to my system to fix a problem but I have no idea how to get this patch and then apply it. Can anybody help me please? Patch: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c11e5f35ab490bd30591563816fbc83526521777
First, download the patch. There is a handy patch button on the link you indicated. Say for instance, you saved it to /tmp/foo.patch cd into the source directory and run the following cd drivers/gpu/drm/i915/intel_pm.c patch -p1 < /tmp/foo.patch You could alternatively use git-am to create and apply the patch. Assuming you have checked out the linux kernel. https://www.kernel.org/pub/software/scm/git/docs/git-am.html Resources Applying Patches Building Kernel
How do I apply this revert commit patch from git?
1,498,581,374,000
I have a project with a lot of submodules and I want to delete all remote branches named foo in the submodules, if it exists. I am trying to following: git submodule foreach git push origin :foo This works as intended if the branch exists in all submodules, but if any of the submodules is missing the branch, the foreach stops: Stopping at 'modules/bar'; script returned non-zero status. How do I suppress the error?
From the git submodule man page: A non-zero return from the command in any submodule causes the processing to terminate. This can be overridden by adding || : to the end of the command. This means the following should do the job: git submodule foreach 'git push origin :foo || :' The || is an OR and executes the next command if the first one returns non-zero, the : returns true.
Remove branch from all submodules
1,498,581,374,000
Current code to generate change logs: svn2cl --linelen 78 --reparagraph --include-rev --group-by-day The closest I could get with vanilla options is git shortlog --format='* [%h] %s' -w78,8,10 How do I emulate the svn2cl output as closely as possible? Example output: 2013-02-19 username * [r30695] path1: commit message * [r30691] path2, path3, path4: looooooooooooooooooooooooooooong commit message * [r30690] path1, path3: commit message 2013-02-19 other_user * ... 2013-02-18 username * ... Two issues remain: Include a human-readable list of paths before the commit message Pretty-print long commit messages
Another solution gave the right direction. The result so far: #!/usr/bin/env bash while read -r -u 9 date name do echo "$date $name" echo GIT_PAGER=cat git log --no-merges --committer="$name" --since="$date 00:00:00 +0000" --until="$(date --date="$date + 1 day" +%Y-%m-%d) 00:00:00 +0000" --format=' * [%h] %s' echo done 9< <(git log --no-merges --format=$'%cd %cn' --date=short | sort --unique --reverse) The midnight times were necessary. It looks like for some reason it uses the current time instead of the start of the day by default. Two issues remain: Include a human-readable list of paths before the commit message Pretty-print long commit messages Sample output: 2013-02-19 username * [f97bb5f] commit message * [f0e419d] looooooooooooooooooooooooooooong commit message * [070e50f] commit message 2013-02-19 other_user * ... 2013-02-18 username * ...
Git changelog grouped by day and user
1,498,581,374,000
I'm cloning a popular open source project into GitHub, and I only realized this after it was too late. I'm also trying to convert this project over to use Maven instead of Ant/Ivy for a build tool. I was able to convert the repository from SVN to Git via the aptly-named svn2git, then started making changes toward the Maven migration. I failed to realize at the get-go that I needed to create a separate branch for my Maven migrations. Is there a way for me to take my revisions, remove them from master, and send them to a new branch?
This sounds really simple to fix assuming you made all your commits to master. Here's a high-level description of the steps (tailor commands to your specific repo). Make a new branch at your current HEAD (e.g. with git branch <newbranch>) Switch to the current master (git checkout master). Track down your original master HEAD commit and move there (e.g. git reset --hard HEAD~n). When pushing to a remote repository, use --force to foist the undoings onto the repository (for example: git push --force --all)
Revert commits and commit them to a branch?
1,498,581,374,000
I am looking for a formatter to use with my git commits. par pretty much does what I want, with the (important) limitation that I can't get it to properly format bullet lists, which are pretty common in commit messages. For instance: % export PARINIT="rTbgqR B=.,?'_A_a_@ Q=_s>|" % par << EOF heredoc> [JR-1234] This is a fix for the thing. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. - I am a developer that doesn't like linebreaks. I also like bullet lists. I like bullet lists a lot. - I like bullet lists. I like bullet lists a lot. I am also a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. heredoc> EOF This gives output: [JR-1234] This is a fix for the thing. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. - I am a developer that doesn't like linebreaks. I also like bullet - lists. I like bullet lists a lot. I like bullet lists. I like - bullet lists a lot. I am also a developer that doesn't like - linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. While, I would like to have something like this: [JR-1234] This is a fix for the thing. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. - I am a developer that doesn't like linebreaks. I also like bullet lists. I like bullet lists a lot. - I like bullet lists. I like bullet lists a lot. I am also a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. Doing this with par would be ideal, but some other standalone formatter in the same vein would also do.
Pandoc will do that: $ pandoc -t plain <<EOF > [JR-1234] This is a fix for the thing. > > I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. > > - I am a developer that doesn't like linebreaks. I also like bullet lists. I like bullet lists a lot. > - I like bullet lists. I like bullet lists a lot. I am also a developer that doesn't like linebreaks. > > I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. I am a developer that doesn't like linebreaks. > EOF [JR-1234] This is a fix for the thing. I am a developer that doesn’t like linebreaks. I am a developer that doesn’t like linebreaks. I am a developer that doesn’t like linebreaks. - I am a developer that doesn’t like linebreaks. I also like bullet lists. I like bullet lists a lot. - I like bullet lists. I like bullet lists a lot. I am also a developer that doesn’t like linebreaks. I am a developer that doesn’t like linebreaks. I am a developer that doesn’t like linebreaks. I am a developer that doesn’t like linebreaks.
text formatter that supports bullets
1,498,581,374,000
Appologies for the vague title. I frequently execute git branch throughout the day, and it seems at some point recently (perhaps in the past month?) the behavior has changed. I recall previously git branch would print the list of branches and immediately return to a prompt -- however it now appears to be printing the branches within less, and requiring me to press Esc before returning to the command prompt. I'm uncertain if this is a change to git branch itself, or perhaps my default less flags -- or possible some other factor. I've observed this on: Debian bullseye, git 2.30.2 macOS Montegery, git 2.34.1 In both cases less' default flags haven't been customized by me, and are: LESS="-g -i -M -R -S -w -X -z-4" And running git branch in any git repo will print the branches as expected, with less's summary of lines 1-X/X (END) at the bottom of the console. Pressing h shows the less help prompt--confirming it is less that's being used. Is this a recent change? Is there a git option to avoid using less--or a less option/flag to have it automatically exit if there's less than one screen of data?
git branch defaults to using a pager since version 2.16. You can configure that by changing pager.branch, e.g. git config --global pager.branch false or on an ad-hoc basis by adding the -P (--no-pager) option. less does have an option to exit if the data it is asked to display fits on a single screen, -F. When the LESS environment variable is not set, git sets it to FRX by default, which includes this behaviour.
Is `git branch` using `less` a recent change? Or is `less` behaving differently recently?
1,639,406,504,000
I'm using git aliases from zsh plugins: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git So it has git aliases like: gst # git status ga # git add gc "commit" # git commit -v "commit" ... ...and I'm also using git bare repo to backup all my dotfiles: https://github.com/Anthonyive/dotfiles/blob/0706bc81daa3aeb7899b506cd89d4ab78fc7b176/USAGE.md In particular, the git bare repo technique aliases the git command to dotfiles: alias dotfiles='git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME' alias d='dotfiles' So then how do I map the all the git alias command to d? Like: dst # similar to gst, but uses the dotfiles alias da # similar to ga dc "commit" # similar to gc "commit" ... Mapping them one by one seems very tedious...
The associative array aliases contains all alias definitions. for name in "${(@k)aliases}"; do if [[ $name == g* && $aliases[$name] == 'git '* ]]; then alias d${name#g}="dotfiles ${aliases[$name]#git }" fi done Alternatively, you could change the d alias to a function that expects a following git command, but first expands shell aliases and removes any leading git. alias d='d ' # expand aliases after d function d { if [[ $1 == "git" ]]; then shift; fi dotfiles "$@" } Then d gst will run dotfiles status, d gc myfile will run dotfiles commit myfile, d ls-tree will run dotfiles ls-tree, etc. Completion is doable but not easily.
Create new set of aliases based on current set of aliases (eg. gst -> dst)?
1,639,406,504,000
I need to test a debugging tool on a variety of outdated distributions. I managed to install build-essential package on Debian Squeeze. The problem though is now that it's impossible to download sources from GitHub/GitLab with either git or curl/wget. The reason is simple - deprecation of the older SSL protocols, while curl or git don't know newer protocols. Is it possible to workaround this for the CI job that needs to do git clone or curl <gittag>.zip? You can see current GitHub Actions CI configuration for Debian Wheezy and Debian Jessie.
In wheezy, git depends on libcurl3-gnutls 7.26.0 which in turn depends on libgnutls26 2.12.17. Curl depends on libssl1.0.0 1.0.1 (that's OpenSSL). These series are very out of date and I don't think current versions have a compatible ABI. So just compiling SSL libraries and putting them in /usr/local won't cut it. If you only need a download tool, you could compile a current version of wget or curl with a statically linked openssl. For git this may be harder. The easy brute-force approach is to arrange two installations that share a filesystem, for example installing one in a chroot. For your use case, it may be easier to have one CI action to do the initial downloading on a modern system and store the data locally, then have another CI action for the build and test on the obsolete system.
How to use curl/git in Debian Squeeze with modern HTTPS?
1,639,406,504,000
I use git to track my dotfiles across multiple machines. I wrote a pretty simple script in the repo, which backs up any outdated existing dotfiles and then creates symbolic links to each of the up-to-date dotfiles. Here is the script: #!/bin/bash ############################ # makesymlinks.sh # This script creates symlinks from the home directory to any desired dotfiles in ~/dotfiles ############################ ########## Variables dir=~/dotfiles # dotfiles directory olddir=~/dotfiles_old # old dotfiles backup directory files="bash_aliases bashrc vimrc" # list of files/folders to symlink in homedir ########## # create dotfiles_old in homedir echo "Creating $olddir for backup of any existing dotfiles in ~" mkdir -p $olddir # move any existing dotfiles in homedir to dotfiles_old directory, then create symlinks echo "Moving any existing dotfiles from ~ to $olddir" for file in $files; do if [ -f ~/."$file" ]; then mv -n ~/."$file" ~/dotfiles_old/ #-n option means don't overwrite existing files in dotfiles_old fi #if e.g. ~/.vimrc exists after mv command, then this script must've been run before w/ .vimrc included if [ -f ~/."$file" ]; then echo "Symlink to $dir/$file already exists" else echo "Creating symlink to $dir/$file in ~" ln -s $dir/"$file" ~/."$file" fi done # source .bashrc printf "\nTo complete the setup, please run the following command:\n\n" printf "\tsource ~/.bashrc\n\n" This script normally works just fine. Today though I started working on a new machine (remotely through TeamViewer if that matters), and when I ran this script for the first time, it deleted the directory it was in. I have no idea how it could've done that given the script I wrote, and it worked correctly the second time I ran it (after re-cloning the repository again). What went wrong, and how can I fix it? Was this somehow git's fault? Here's what my bash terminal looked like surrounding the bug (I've added some commentary with bash comments here for clarity): drakeprovost@shatterdome:~/RoverCoreOS$ git clone https://github.com/DrakeProvost/dotfiles.git Cloning into 'dotfiles'... remote: Enumerating objects: 42, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (30/30), done. remote: Total 42 (delta 21), reused 29 (delta 11), pack-reused 0 Unpacking objects: 100% (42/42), done. drakeprovost@shatterdome:~/RoverCoreOS$ cd dotfiles/ drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ls bash_aliases bashrc makesymlinks.sh README.md vimrc drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ./makesymlinks.sh Creating /home/drakeprovost/dotfiles_old for backup of any existing dotfiles in ~ Moving any existing dotfiles from ~ to /home/drakeprovost/dotfiles_old Creating symlink to /home/drakeprovost/dotfiles/bash_aliases in ~ Creating symlink to /home/drakeprovost/dotfiles/bashrc in ~ Creating symlink to /home/drakeprovost/dotfiles/vimrc in ~ To complete the setup, please run the following command: source ~/.bashrc drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ls bash_aliases bashrc makesymlinks.sh README.md vimrc drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ cd drakeprovost@shatterdome:~$ ls -al #.bashrc, .vimrc, and .bash_aliases were all red symlinks here, meaning they pointed to non-existent files. Also note that the dotfiles directory has disappeared total 144 drwxr-xr-x 26 drakeprovost drakeprovost 4096 Jul 19 22:40 . drwxr-xr-x 12 root root 4096 Sep 24 2019 .. lrwxrwxrwx 1 drakeprovost drakeprovost 40 Jul 19 22:40 .bash_aliases -> /home/drakeprovost/dotfiles/bash_aliases -rw------- 1 drakeprovost drakeprovost 11400 Feb 27 20:01 .bash_history -rw-r--r-- 1 drakeprovost drakeprovost 220 Sep 17 2019 .bash_logout lrwxrwxrwx 1 drakeprovost drakeprovost 34 Jul 19 22:40 .bashrc -> /home/drakeprovost/dotfiles/bashrc drwx------ 15 drakeprovost drakeprovost 4096 Oct 15 2019 .cache drwxr-xr-x 5 drakeprovost drakeprovost 4096 Feb 20 18:08 catkin_ws drwxr-xr-x 5 drakeprovost drakeprovost 4096 Feb 27 19:23 catkin_ws_PMCurdf drwx------ 13 drakeprovost drakeprovost 4096 Feb 27 18:57 .config drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Desktop drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Documents drwxr-xr-x 2 drakeprovost drakeprovost 4096 Jul 19 22:40 dotfiles_old drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Downloads -rw-r--r-- 1 drakeprovost drakeprovost 8980 Sep 17 2019 examples.desktop drwx------ 2 drakeprovost drakeprovost 4096 Oct 15 2019 .gconf drwx------ 3 drakeprovost drakeprovost 4096 Oct 15 2019 .gnupg -rw------- 1 drakeprovost drakeprovost 2052 Jul 19 22:31 .ICEauthority drwx------ 3 drakeprovost drakeprovost 4096 Oct 15 2019 .local drwx------ 5 drakeprovost drakeprovost 4096 Oct 15 2019 .mozilla drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Music drwx------ 6 drakeprovost drakeprovost 4096 Jul 19 22:31 .nx drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Pictures -rw-r--r-- 1 drakeprovost drakeprovost 807 Sep 17 2019 .profile drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Public drwx------ 2 drakeprovost drakeprovost 4096 Jul 19 22:31 .qt drwxr-xr-x 4 drakeprovost drakeprovost 4096 Feb 27 19:58 .ros drwxr-xr-x 11 drakeprovost drakeprovost 4096 Jul 19 22:40 RoverCoreOS drwxr-xr-x 2 drakeprovost drakeprovost 4096 Feb 13 13:45 .rviz drwxr-xr-x 3 drakeprovost drakeprovost 4096 Oct 15 2019 snap drwx------ 2 drakeprovost drakeprovost 4096 Oct 15 2019 .ssh -rw-r--r-- 1 drakeprovost drakeprovost 0 Oct 15 2019 .sudo_as_admin_successful drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Templates drwxr-xr-x 2 drakeprovost drakeprovost 4096 Oct 15 2019 Videos -rw------- 1 drakeprovost drakeprovost 761 Oct 15 2019 .viminfo lrwxrwxrwx 1 drakeprovost drakeprovost 33 Jul 19 22:40 .vimrc -> /home/drakeprovost/dotfiles/vimrc drakeprovost@shatterdome:~$ source ~/.bashrc bash: /home/drakeprovost/.bashrc: No such file or directory drakeprovost@shatterdome:~$ git clone https://github.com/DrakeProvost/dotfiles.git Cloning into 'dotfiles'... remote: Enumerating objects: 42, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (30/30), done. remote: Total 42 (delta 21), reused 29 (delta 11), pack-reused 0 Unpacking objects: 100% (42/42), done. drakeprovost@shatterdome:~$ cd dotfiles drakeprovost@shatterdome:~/dotfiles$ ./makesymlinks.sh Creating /home/drakeprovost/dotfiles_old for backup of any existing dotfiles in ~ Moving any existing dotfiles from ~ to /home/drakeprovost/dotfiles_old Creating symlink to /home/drakeprovost/dotfiles/bash_aliases in ~ Symlink to /home/drakeprovost/dotfiles/bashrc already exists Creating symlink to /home/drakeprovost/dotfiles/vimrc in ~ To complete the setup, please run the following command: source ~/.bashrc drakeprovost@shatterdome:~/dotfiles$ cd drakeprovost@shatterdome:~$ ls #notice that dotfiles still exists this time catkin_ws Documents Downloads Pictures snap catkin_ws_PMCurdf dotfiles examples.desktop Public Templates Desktop dotfiles_old Music RoverCoreOS Videos drakeprovost@shatterdome:~$ source ~/.bashrc #this now works like you would expect drakeprovost@shatterdome:~$
Here's the output in your question annotated: drakeprovost@shatterdome:~/RoverCoreOS$ git clone https://github.com/DrakeProvost/dotfiles.git Cloning into 'dotfiles'... remote: Enumerating objects: 42, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (30/30), done. remote: Total 42 (delta 21), reused 29 (delta 11), pack-reused 0 Unpacking objects: 100% (42/42), done. NOTE: you were in the directory ~/RoverCoreOS when you ran the above git clone so the above created the directory ~/RoverCoreOS/dotfiles, not ~/dotfiles. drakeprovost@shatterdome:~/RoverCoreOS$ cd dotfiles/ drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ls bash_aliases bashrc makesymlinks.sh README.md vimrc drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ./makesymlinks.sh Creating /home/drakeprovost/dotfiles_old for backup of any existing dotfiles in ~ Moving any existing dotfiles from ~ to /home/drakeprovost/dotfiles_old Creating symlink to /home/drakeprovost/dotfiles/bash_aliases in ~ Creating symlink to /home/drakeprovost/dotfiles/bashrc in ~ Creating symlink to /home/drakeprovost/dotfiles/vimrc in ~ To complete the setup, please run the following command: source ~/.bashrc drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ ls bash_aliases bashrc makesymlinks.sh README.md vimrc All of the above happened in ~/RoverCoreOS/dotfiles. drakeprovost@shatterdome:~/RoverCoreOS/dotfiles$ cd You are now in the directory ~ drakeprovost@shatterdome:~$ ls -al #.bashrc, .vimrc, and .bash_aliases were all red symlinks here, meaning they pointed to non-existent files. Also note that the dotfiles directory has disappeared ~/dotfiles didn't disappear, it never existed. ~/RoverCoreOS/dotfiles existed and presumably still exists. ... drakeprovost@shatterdome:~$ git clone https://github.com/DrakeProvost/dotfiles.git Cloning into 'dotfiles'... remote: Enumerating objects: 42, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (30/30), done. remote: Total 42 (delta 21), reused 29 (delta 11), pack-reused 0 Unpacking objects: 100% (42/42), done. Now you've created the directory ~/dotfiles and from here on things work as you expect. I'd recommend you modify your script to add some defensive checks. They can't stop you from doing the above but they can at least alert you of some issues and they would have caught the above problem (assuming you didn't have an old dotfiles directory with the expected files in your HOME dir), e.g.: [[ -d "$dir" ]] || { ret="$?"; echo "dir \"$dir\" does not exist"; exit "$ret"; } for file in $files; do [[ -s "$dir/$file" ]] || { ret="$?"; echo "file \"$dir/$file\" does not exist or is empty"; exit "$ret"; } done # create dotfiles_old in homedir echo "Creating $olddir for backup of any existing dotfiles in ~" mkdir -p "$olddir" || { ret="$?"; echo "Failed to create olddir \"$olddir\""; exit "$ret"; } You can add other defensive checks like that as you see fit.
My dotfiles bash script somehow deleted its own directory?
1,639,406,504,000
I'm trying to configure my own git repository server with Git SmartHTTP and Apache2. So followed these instuctions from the official git manual. But during the configuration it becomes not clear to me, what the GIT_PROJECT_ROOT variable exactly configures: Does it set the path to exactly one repository on a webserver or can you set it's value to a folder path which contains all your repositories. And what other things does this variable affects? The problem is that there is no description or explanation in the official git manual neither in the SmartHTTP chapter nor in the environment variables chapter.
There is a description in the git-http-backend manual. Variable GIT_PROJECT_ROOT is set to a parent path of all repositories and similar to the Apache DocumentRoot directive, it is used to translate an URL-path to the filesystem: URL TRANSLATION To determine the location of the repository on disk, git http-backend concatenates the environment variables PATH_INFO, which is set automatically by the web server, and GIT_PROJECT_ROOT, which must be set manually in the web server configuration. If GIT_PROJECT_ROOT is not set, git http-backend reads PATH_TRANSLATED, which is also set automatically by the web server. EXAMPLES All of the following examples map http://$hostname/git/foo/bar.git to /var/www/git/foo/bar.git. Apache 2.x Ensure mod_cgi, mod_alias, and mod_env are enabled, set GIT_PROJECT_ROOT (or DocumentRoot) appropriately, and create a ScriptAlias to the CGI: SetEnv GIT_PROJECT_ROOT /var/www/git SetEnv GIT_HTTP_EXPORT_ALL ScriptAlias /git/ /usr/libexec/git-core/git-http-backend/ So the /git/ part in http://hostname/git/foo/bar.git is mapped to the git-http-backend CGI script and the remaining part foo/bar.git is appended to the path of the GIT_PROJECT_ROOT (or DocumentRoot) variable which should match a Git repo.
Git repository server GIT_PROJECT_ROOT
1,639,406,504,000
I have the following lines in my ~/.aliases: function __function_exists() { declare -f -F $1 > /dev/null return $? } # git aliases (need to have git bash completion installed) for al in `__git_aliases`; do alias g$al="git $al" complete_func=_git_$(__git_aliased_command $al) __function_exists $complete_fnc && __git_complete g$al $complete_func done And in my ~/.gitconfig i have: [alias] # one-line log l = log --pretty=format:"%C(yellow)%h\\ %ad%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate --date=short a = add ap = add -p c = commit --verbose ca = commit -a --verbose cm = commit -m cam = commit -a -m m = commit --amend --verbose d = diff ds = diff --stat dc = diff --cached s = status -s co = checkout cob = checkout -b # list branches sorted by last modified b = "!git for-each-ref --sort='-authordate' --format='%(authordate)%09%(objectname:short)%09%(refname)' refs/heads | sed -e 's-refs/heads/--'" # list aliases la = "!git config -l | grep alias | cut -c 7-" And in my ~/.zshrc: zstyle :compinstall filename '/home/giuliani/.zshrc' autoload -Uz compinit compinit [[ -f $HOME/.aliases ]] && source "$HOME/.aliases" So, for each alias in my gitconfig i will define a shell alias like gl for git log and so on. Trying to port this to zsh i'm having a problem: zsh autoload built-in only loads the file /usr/share/zsh/functions/Completion/Unix/_git the first time i try to complete some git command. I've tried to call/load _git file directly from the .zshrc but other them a few warnings, it didn't work. What is the proper way to have the same funcionality that i have in bash, using zsh ?
Actually, calling _git from your .zshrc does work, in that it defines _git and its companion functions including __git_aliases, and it tries to do some completion but fails (without even an error message in this particular case). This works with most completion functions. You need to do this after compinit so that _git and its auxiliary functions are marked for autoloading. % zsh -f darkstar% autoload compinit darkstar% compinit darkstar% _git darkstar% __git_aliases _tags:comptags:36: can only be called from completion function _tags:comptry:55: can only be called from completion function _tags:comptags:60: can only be called from completion function _tags:comptags:67: can only be called from completion function The problem is that when you run __git_aliases, it calls builtins that can only be used while doing completion. You can work around that by temporarily defining functions with the same name as these builtins that do just the part that you want to do, which is often nothing, but it is very clumsy. I'm not going to show how because there's a much simpler way in this particular case. Since you're diving deep into the _git completion file anyway, call __git_extract_aliases instead of __git_aliases. __git_extract_aliases stuffs information into the variable aliases in a way that's easy to extract. (Note: I wrote this answer for zsh 5.4.2, which is the version on Ubuntu 18.04. Other versions of zsh may have different structure in _git.) _git 2>/dev/null define_git_aliases () { local -a aliases; local al __git_extract_aliases for al in ${aliases%%:*}; do alias g$al="git $al" done } define_git_aliases That's still a lot more effort that necessary, and potentially extra porting effort to cope with different versions of zsh. __git_extract_aliases is basically one line of code. for al in ${${${(0)"$(git config -z --get-regexp '^alias.')"}%%$'\n'*}#alias.}; do alias g$al="git $al" done
Define git aliases based on gitconfig in zsh
1,639,406,504,000
I am aware that it is possible to forward SSH from server A to server B by creating a tunnel. What I am asking for is rather the red alternative on the schema above. Can this scenario be implemented: SSH to server A Server A tells client to go to server B instead Server B communicates directly with client over SSH So basically a sort of proxy that after introducing the client-server to each other, he gets out of the communication. I imagine using a firewall redirection doesn't offer much customization. What I seek ultimately is a way to make access through SSH to git mirrors transparent for client depending on geolocation. Advanced scenario scenario Client Pulling from server A and is closer to server B is redirected to B When pushing, client remains on server A
Unfortunately there is no flag to turn on in SSH to do this. You'd have to code something custom for GIT. (i.e. if serverA has lower ping time than server B use A or vice vera)
Is it possible to redirect ssh traffic (not forward), How?
1,639,406,504,000
I've just run tar x by mistake instead of tar c, and overwrote my git repo with a few days older version. This will have left alone any files I had newly created though, including objects in .git. How can I recover as much as possible?
Make a copy of the whole mess first, just in case. git fsck will show dangling objects and commits. Find the newest dangling commit. I fed all the commit hashes to gitk, and it just shows the most "recent" one at the top. As well as only having a few commits to deal with, I only had a single branch to recover - this would be more complex if there was more than one head. Then git stash to stash currently uncommitted changes for inspection. I was then able to git reset --hard to the commit hash determined above. git stash pop also merged back pretty cleanly. I think I got pretty much everything I wanted back again.
Recover a git repo which was overwritten with an older version
1,639,406,504,000
Studying the Github backup-utils I found the command bm_start inside their scripts. This is an example that uses the bm_start and bm_end, with some other code between them. According to the project page, the pre-requisite to use the scripts is: Linux or other modern Unix operating system with bash, git, OpenSSH, and rsync v2.6.4 or newer. Where does this command come from? How does it work? I could not find references to bm_start with man or apropos, nor by Googling it.
They're shell functions defined in share/github-backup-utils/bm.sh, pulled in via share/github-backup-utils/ghe-backup-config.
What does "bm_start" do in a bash script?
1,639,406,504,000
I would like to do something like: git clone https://github.com/meteor{A,B,C,D}test but bash does not convert the {} into an each. What am I doing wrong?
The syntax you are using {A,B,C,D} is valid, but it results in argument splitting. Meaning your command will be run as: git clone https://github.com/meteorAtest https://github.com/meteorBtest https://github.com/meteorCtest https://github.com/meteorDtest What you want is to run 4 different commands. One simple way to do this is a for loop. for url in https://github.com/meteor{A,B,C,D}test; do git clone "$url"; done
Clone repos with a similar name
1,639,406,504,000
I want to be able to push a repository to Github at midnight, every night. I know that Github isn't a back-up service, and, in no way am I expecting it to be this - I just want the best up-to-date version on Github and this works for me, and, my team. What I was thinking is this: Creating a Bash script that pushes the repository to Github normally In Crontab, execute the script at midnight every day of the week. Would this be the best method to use? If so, this seems easy enough to do. My next problem :) I want an email to be sent to me, after the repository has been pushed, so it would just send an email saying: "Repository Pushed.. Ok" or if there was a problem, it would alert me to this. Is this possible? If so, could anyone please provide some examples of how to do this. Hope someone can help :)
As the links described as harish.venkat Create a script /path_to_script, which would add new file, commit and push. #!/bin/sh cd /location/of/clone git add * if [[ $? != 0 ]] then mail -s "add failed" [email protected] exit 1 fi git commit -a -m "commit message, to avoid being prompted interactively" if [[ $? != 0 ]] then mail -s "commit failed" [email protected] exit 1 fi git push if [[ $? != 0 ]] then mail -s "push failed" [email protected] exit 1 fi mail -s "push ok" [email protected] Change the script to executable, chmod a+x /path_to_script Use crontab -e and add below line # run every night at 03:00 0 3 * * * /path_to_script
Crontab with Github
1,639,406,504,000
Whenever I tab-complete a file path after a git command in bash, e.g. git add, I have to press <TAB> multiple times to complete to the actual filename, depending on how many subfolders there are up to the file. Example: I want to add the file my/example/file, then I enter: git add <TAB> git add my/<TAB> git add my/example/<TAB> git add my/example/file This is the case even when my/example/file is the only changed file and hence the only current tab-completion option. In this case bash could as well complete the full path with the first <TAB> already, but it doesn't. fish actually does this by default: git add <TAB> git add my/example/file Is there a way to configure this behavior in bash as well? I am on Ubuntu 20.04 using its default bash completions.
One way to accomplish this would be to copy the git completion script, /usr/share/bash-completion/completions/git, to ~/.local/share/bash-completion/completions/ and modify it to complete with full index paths: mkdir -p ~/.local/share/bash-completion/completions cd ~/.local/share/bash-completion/completions cp /usr/share/bash-completion/completions/git . # See diff below patch -lp0 </tmp/index_paths.diff echo GIT_COMPLETION_FULL_INDEX_PATHS=1 >>~/.bashrc exec bash As far as I can tell the changes required are: Modify __git_index_files() so that it outputs full index paths rather than just the first path component. In __git_complete_index_file(), stop using __gitcomp_file_direct to set COMPREPLY because it uses compopt -o filenames, which only outputs basenames. This option was also taking care of shell quoting, so do that manually now. Note that __git_complete_index_file is used for the completion of several other git commands other than add such as clean, commit, and rm, so the full path completion will apply to those too. Here's the diff of my attempt at these changes, which adds the functionality behind the shell variable GIT_COMPLETION_FULL_INDEX_PATHS: --- git +++ git @@ -39,6 +39,11 @@ # When set to "1", do not include "DWIM" suggestions in git-checkout # and git-switch completion (e.g., completing "foo" when "origin/foo" # exists). +# +# GIT_COMPLETION_FULL_INDEX_PATHS +# +# Normally index path completions return only the next path component. When +# set to "1", the whole path will be completed. case "$COMP_WORDBREAKS" in *:*) : great ;; @@ -435,6 +440,19 @@ __gitcomp_nl_append "$@" } +# Shell quotes each word and fills the COMPREPLY array. +# 1: List of newline-separated completion words. +__gitcomp_quote_direct () +{ + local IFS=$'\n' + local quoted="$1" + [[ -n $1 ]] && quoted=$(printf '%q\n' $1) + + COMPREPLY=($quoted) + + compopt +o nospace 2>/dev/null || true +} + # Fills the COMPREPLY array with prefiltered paths without any additional # processing. # Callers must take care of providing only paths that match the current path @@ -503,10 +521,12 @@ __git_index_files () { local root="$2" match="$3" + local field=1 + [ "$GIT_COMPLETION_FULL_INDEX_PATHS" = "1" ] && field=0 __git_ls_files_helper "$root" "$1" "$match" | awk -F / -v pfx="${2//\\/\\\\}" '{ - paths[$1] = 1 + paths[$f] = 1 } END { for (p in paths) { @@ -518,19 +538,13 @@ # The path is quoted. p = dequote(p) - if (p == "") - continue - # Even when a directory name itself does not contain - # any special characters, it will still be quoted if - # any of its (stripped) trailing path components do. - # Because of this we may have seen the same directory - # both quoted and unquoted. - if (p in paths) - # We have seen the same directory unquoted, - # skip it. - continue - else + # When not using full index paths, p in paths is checked + # because the dequoted directory name may already be in + # paths. This is the case when the directory name itself + # does not contain special characters, but a (stripped) + # trailing path component does. + if (p != "" && (f == 0 || !(p in paths))) print pfx p } } @@ -573,7 +587,7 @@ out = out p return out - }' + }' "f=$field" } # __git_complete_index_file requires 1 argument: @@ -595,7 +609,11 @@ cur_="$dequoted_word" esac - __gitcomp_file_direct "$(__git_index_files "$1" "$pfx" "$cur_")" + if [ "$GIT_COMPLETION_FULL_INDEX_PATHS" = "1" ]; then + __gitcomp_quote_direct "$(__git_index_files "$1" "$pfx" "$cur_")" + else + __gitcomp_file_direct "$(__git_index_files "$1" "$pfx" "$cur_")" + fi } # Lists branches from the local repository.
bash tab-completion: complete full path on single tab in git commands?
1,639,406,504,000
My scenario is as follows: After updating files on my Git repository, I have a Git hook that calls an API from my web server. This API performs a Git pull and then I have a Git hook post-merge that restart the web server (Gunicorn). The restart of the web server should occurs a few seconds after the pull is completed otherwise the web server is shutting down before the API call is completed and that returns an error to the Git hook. Currently I worked out the following solution but I am not happy with it. The file .git/hooks/post-merge #!/bin/sh /var/www/tempcollect/.git/hooks/restart > /var/www/tempcollect/.git/hooks/restart.log & The file .git/hooks/restart sleep 10s /usr/bin/sudo systemctl restart tempcollect I would prefer to have the command to restart the web server in the post-merge file. The execution of the file post-merge is started by Git at the end of the pull, thus I have no control on the way it is started.
Finally I ended up with this one line in the file .git/hooks/post-merge #!/bin/sh ( sleep 10 ; /usr/bin/sudo systemctl restart tempcollect ) &
Add a delay in git post-merge
1,639,406,504,000
When I edit a file, and then want to undo my changes, I use git checkout -- file.txt the problem is that git does not keep the file permissions of the existing file. file.txt has permissions 644, but after git checkout it has 600 (which I think comes from my umask) I know git does not store file permissions, and I am not expecting to remember permissions when creating new file. But in this case the file exists.Why can't git keep the permissions as they are? Could this be solved with some ugly hack (some hook) ?
When Git checks out files, it by default uses the umask of the file on the system, setting the executable bit if it's a directory or it's marked as an executable file. That's because Git removes and re-creates the file, so it doesn't preserve the permissions of the existing file. This is actually by design, because there's an option, core.sharedRepository, that lets you configure the permissions of files to be checked out. By default, it is set to umask, which means to use your umask. If you want different behavior in your repository, you can set it differently, such as to 0644, which will use that value. It is possible to use a post-checkout hook to change the permissions back if you want, although this may not work in all cases.
git checkout -- file changes permissions for existing file
1,639,406,504,000
I am using a Debian 9 server. Usually I access via ssh to a normal user (say user1) and su into root, because I disabled ssh into root. Lately I was setting up a git-server where I created a user git with the group git and restricted him to git-shell. Playing around a little while I added user1 to the group git like this: usermod -aG git user1 This worked alright, user1 was member of the groups user1 and git. At the end I wanted to undo this, so I used: usermod -G user1 user1 Shortly after this, I lost my internet connection and had to reconnect. I can ssh into user1 alright, but when using su to access root, there is an error: user1@hostname:~$ su Password: Cannot execute git: No such file or directory user1@hostname:~$ I included the information about git-shell, because I have no idea what else could be the reason. Hopefully it is not all lost and somebody can help me to regain control. PS: There isn't any other root-like user, so sudo isn't working, since user1 "is not in the sudoers file". PPS: I could reset the root password via VPS-login, but I am not quite sure whether this is going to work or make everything worse.
Solved only with rescue mode: boot into "rescue mode" - probably available at most VPS mount appropiate drive nano /path/to/mounted/drive/etc/passwd change root entry to root:x:0:0:root:/root:/bin/bash save, exit and reboot without rescue mode Different approaches like user1@hostname: ~$ su -s /bin/sh or user1@hostname: ~$ su -s /bin/sh -c /bin/sh did not work and only replied with the same error message. I did not find the reason (yet), but based on the comments of @doneal24 I regained control over my system. If i can clearify the reason, I will provide the details - see edit below. REPRODUCING: I (accidentally) found out how I changed the root shell. According to this from ProGit, I thought chsh -s $(command -v git-shell) <user> is enabling the git-shell for input. But inserting git for <user> changes the shell for root. root@hostname ~ # chsh -s $(git init ./project1.git git-shell) git usage: git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>] chsh: Warning: git does not exist root@hostname ~ # I probably misinterpreted the information on ProGit, because this seems a lot like what I wrote under EDIT. EDIT1: See below on how it actually will be changed. root@hostname ~# chsh root -s git chsh: Warning: git does not exist root@hostname ~# changed the entry to root@hostname~ # cat /etc/passwd | grep root root:x:0:0:root:/root:git root@hostname~ # which is curious, as something like root@hostname ~# chsh root -s /bin/bash Password: chsh: PAM: Authentication failure root@hostname ~# is not working.
Cannot su into root default shell - Debian
1,639,406,504,000
I'm expecting Git to create a merge commit when I merge a signed or annotated tag but instead it fast-forwards the branch pointer. I'm using Git version 2.17.0 on openSUSE Tumbleweed that comes with it. According to the manpage of git-merge(1) it should create a merge commit in case of merging a signed/annotated tag: --no-ff Create a merge commit even when the merge resolves as a fast-forward. This is the default behaviour when merging an annotated (and possibly signed) tag that is not stored in its natural place in refs/tags/ hierarchy. The sequence of commands which I issued looks like this: git init foobar cd foobar git commit --allow-empty -m 'Empty root commit' git checkout -b feature git commit --allow-empty -m 'Feature one commit ahead of master' git tag -a -m 'Feature ready for non fast-forward merge' ready-to-merge-feature git checkout master git merge ready-to-merge-feature Unfortunately and unexpectedly the merge of the annotated tag ready-to-merge-feature does result in a fast-forward merge instead of creating a merge commit. The same unexpected behavior I observe with a signed instead of an annotated tag. Are my assumptions wrong? Am I doing something wrong? What would be a solution?
Note the part of the manpage that you'd quoted that I've bolded below: This is the default behaviour when merging an annotated (and possibly signed) tag that is not stored in its natural place in refs/tags/ hierarchy. With the command sequence that you gave, the tag would be in its natural place, so the conditions for that default wouldn't apply. This default was put in place to aid fetching a tag from a contributors repository as FETCH_HEAD in the maintainer's repository. Such tags are likely to be ephemeral, so if they have content (an annotation and/or signature) it's usually good to preserve that information in a merge commit. But, tags that are already under refs/tags/ are likely to be part of the permanent state of the project, and thus the content should remain available without needing to be transferred to a commit. The simplest solution would probably be to explicitly use the --no-ff option.
Git not creating merge commit when merging signed/annotated tag
1,639,406,504,000
Here is my error: fatal: cannot update the ref 'HEAD': unable to append to '.git/logs/HEAD': Invalid argument Etckeeper worked until today. The only recent change to the system has been the upstream git repository. The .git directory is now on an sshfs mount. I now understand that's related to the problem. The problem started when the .git directory was switched from an NFS mount to an sshfs mount. Full output of the command giving the error: [root@pc2 etc]# pacman -R cowsay checking dependencies... Packages (1) cowsay-3.03-9 Total Removed Size: 0.03 MiB :: Running pre-transaction hooks... (1/3) Performing snapper pre snapshots for the following configurations... ==> root: 182 (2/3) Etckeeper Pre-install (3/3) Update git tracked list of installed packages fatal: cannot update the ref 'HEAD': unable to append to '.git/logs/HEAD': Invalid argument error: command failed to execute correctly :: Processing package changes... (1/1) removing cowsay [#################################################################] 100% :: Running post-transaction hooks... (1/4) Etckeeper Post-install (2/4) Update git tracked list of installed packages fatal: cannot update the ref 'HEAD': unable to append to '.git/logs/HEAD': Invalid argument error: command failed to execute correctly (3/4) Arming ConditionNeedsUpdate... (4/4) Performing snapper post snapshots for the following configurations... ==> root: 183 Please suggest a next step.
When you use sshfs to mount the directory, also specify -o writeback_cache=no: sshfs -o writeback_cache=no [user@]host:/dir/ /localdir See https://github.com/libfuse/sshfs/issues/82 for more.
Git repository on SSHFS: unable to append to '.git/logs/HEAD': Invalid argument
1,639,406,504,000
For example: I have a kernel 3.16 from my embedded support, but I want to have some network wireless drivers from 3.19. What is the best way to merge only this drivers (not full kernel)? I tried merge, but it results in many conflicts. Copying files from 3.19 to 3.16 is a lot of work and results in many missing functions. I have to copy includes also, and these includes needs other includes and new functions, etc. This is a never ending work or never working. I tried to make a diff between some commits and try to cherry-pick them, but I'm not sure that git diff A..B is really working. Sometimes we have merges between A..B with different branches and it's a real mess to consider "what is what". On the other hand, I have to decide which cherry-pick is important for wireless driver and which isn't. Is there any better way?
Finally the best option for me was : Copy drivers files from 3.19 into 3.16 directly. Before commit, thanks to git difftool check every change with previous code. If change uses newer kernel function then get back to older function or add newer function files from 3.19 kernel Compile - if errors then get back to 2. Test. Commit changes.
Merging part of kernel - best way?
1,639,406,504,000
I have the problem, that we login to the systems as our own users johndoe and then have to do a sudo su - root to be able to do administrative tasks. We have the system config files in a git repository (which makes everything better). But now I lose the settings in the user's (johndoe) /home/johndoe/.gitconfig file. I tried to set the $GIT_CONFIGvariable which works, but this is only for setting the repo configuration, not the global one and therefore the for me important variables won't be set: $ sudo su - root Hello johndoe. Switching your .gitconfig to /home/johndoe/.gitconfig # git config --get user.name John Doe # git config --get user.email [email protected] # git config --global --get user.name # git config --global --get user.email # This is the trick I tried: $ cat .bashrc --- snip --- # load git config of user LOGINUSER=$(who am i|awk '{print $1}') if [ "$LOGINUSER" != "root" ]; then GITCFGFILE="/home/$LOGINUSER/.gitconfig" if [ -f $GITCFGFILE ]; then echo "Hello $LOGINUSER. Switching your .gitconfig to $GITCFGFILE" export GIT_CONFIG=$GITCFGFILE fi fi Is there a way to set the path for the global git configuration?
To answer my Question: No This is the solution i ended up with: I added a file /etc/profile.d/gitsetup.sh with the following content: [ -z "$PS1" ] && return [ -z "$BASH_VERSION" -o -z "$PS1" ] && return CFGFILE="/home/$(who am i|awk '{ print $1 }')/.gitconfig" [ $USER == "root" -a -f "$CFGFILE" -a -n "$CFGFILE" ] && cat $CFGFILE > $HOME/.gitconfig It tests on line one and two for an interactive shell, reads the source .gitconfig path on line three and then replaces the roots config file if the source file exists.
Is it possible to set the users .gitconfig (for git config --global) dynamically?
1,639,406,504,000
I am just playing around with bup for my backups and tested it like this: BUP_DIR=/mnt/TestTarget/bup bup init Which gave me the message: Initialized empty Git repository in /mnt/TestTarget/bup/ However in /mnt/TestTarget there seems to be not .git directory. bup index -uv /home/user/TestSource bup save -n buptest1 /home/user/TestSource Now I want to browse the repository with gitk, I did cd /mnt/TestTarget/bup and gitk but it doesn't display anything. gitg gives me Could not find git repository. So what's wrong here? How can I use gitk or gitg to browse my backup?
As @GHugo suggested, using the commands described in my question, produced a backup in ~/.bup. There it is possible to browse it via gitk if you remember to click on tree (and not on patch). Now If one wants a backup in /mnt/TestTarget/bup the following steps worked for me: BUP_DIR=/mnt/TestTarget/bup bup init bup -d /mnt/TestTarget/bup index -uv /home/user/TestSource bup -d /mnt/TestTarget/bup save -n buptest1 /home/user/TestSource Then the data and the index seems to be saved to /mnt/TestTarget/bup and you can cd to it ant execute gitk to browse it (clicking on tree to browse the initial commit). However there is no .git directory in it, so it seems to be a bare repository (correct my if I am wrong).
Browsing bup backup with gitk or gitg
1,639,406,504,000
This repository had a large subdirectory of large files that months ago I removed from the commit and that I now want to remove from the repo forever. The massive subdirectory is no longer in the download but the objects directory is enormous. The checkouts/clones take a long time and I believe this is because of the large .git/objects directory. repo <files to keep> <massive subdirectory> I want to remove the massive subdirectory. https://stackoverflow.com/questions/10067848/remove-folder-and-its-contents-from-git-githubs-history The link above has a long discussion of a procedure that I've put to this script : #!/bin/bash if [ -z "$1" ]; then echo "missing argument: subdirectory to remove" exit fi git filter-branch --tree-filter 'rm -rf $1' --prune-empty HEAD git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d echo $1/ >> .gitignore git add .gitignore git commit -m 'Removing $1 from git history' git gc git push origin master --force I have run this without obvious errors and then cloned the repo to find that the .git/objects directory is not reduced in size. Is the script missing something? Am I missing something? Has a recent version of git introduced a more direct feature for this requirement? Is there another approach?
This answer using index-filter worked for me where the others did not : https://stackoverflow.com/a/32886427/4386557
git remove from repo history a large subdirectory that was removed several commits ago
1,503,604,290,000
I have a NAS (WD MyCloud) which has by default NFS/SMB access enabled. I also have a raspberry pi, that I would like to use as a git server that is addressable over internet using a SSH connection. The data would be stored on the NAS. To sum up: Internet -> router -> raspberry -> NAS I've managed to mount the NAS share with NFS, but when I do this, the NAS never sleeps since it is mounted by the raspberry pi. I only make a few commits, and it would be better if the NAS is active only when needed. Is it possible to achieve this using NFS? using another technology? Is it possible to unmount the NFS share after a time and remount it automatically when needed?
I found this question on my StackExchange profile. Since then, I found the answer I was looking for: Instead of doing NFS mounts, I am now using SSHFS to access the files, which gives me encryption and authentication on the NAS. The public key of the raspberry is saved on the NAS and configured so that I can do a ssh git@cloud without entering a password. user git must have access to the required folders. Then, I am using AutoFS on the raspberry to automatically mount the sshfs when needed. Create /autofs mountpoint mkdir /autofs in /etc/auto.master (user git on the raspberry has UID/GID of 1005/1000, replace accordingly with the UID/GID of the user that will have access to the mountpoint) /autofs /etc/auto.git uid=1005,gid=1000, --timeout=30, --ghost in /etc/auto.git (/nfs/git is the mountpoint on the cloud server) git -fstype=fuse,port=22,rw,allow_other :sshfs\#git@cloud\:/nfs/git then the /autofs/git will point to /nfs/git on the server. A service restart may be required to apply these changes, I don't remember very well.
mount a NAS network share, but let the NAS sleep
1,503,604,290,000
i like to write a oneliner which gets me all remote url from my cloned repositories underneath my git_repo folder (personal git root folder) and to pipe into a file my idea was something like cat */.git/config | grep remote.origin.url= >> git_repos.txt but of course this does not work.
This will list all your remote URLs for remotes named “origin” in any git repositories beneath the current directory: find . -path '*/.git/config' -execdir git remote get-url origin \; It finds files named config inside a .git directory, and from every containing directory, runs git remote get-url origin which shows the remote URL for the “origin” remote in the current repository.
get all git remote.origin.url from exisiting clones in sub directory
1,503,604,290,000
I'm trying to write a bash line that will look at all the subdirectories in my current folder and tell me if any do NOT contain a ".git". Pseudo: for subdir in currentdir if .git does not exist print subdir Here's the one-liner I'm trying, which isn't working and seems to print all the subdirectories: find . -maxdepth 1 -type d -execdir $SHELL -c '[ ! -d ".git" ] && echo "not git repo:" {}' $SHELL -c '{}' ';' I've found some solutions that let me print all subdirectories that HAVE a .git, like this one -- I'm trying to do the opposite. What am I doing wrong? Is this possible?
First, the -execdir command looks wonky (2x $SHELL -c?): $SHELL -c '[ ! -d ".git" ] && echo "not git repo:" {}' $SHELL -c '{}' ';' Also, -execdir runs the command in the directory containing the matched entity, (so the parent directory of the directory that it is checking right now), which is . for all subdirectories. The test is run in the wrong directory. And: You shouldn't reuse {} in exec/-execdir commands. There's no reason to use $SHELL. That's the user's login shell, and it doesn't have any special significance for usage in scripts and such. Just use sh, or bash or ksh if those are your shells of choice, directly. This might work: find . -maxdepth 1 -type d -exec sh -c '! [ -d "$1/.git" ] && echo "not git repo: $1"' _ {} \; The -exec command checks for the existence of .git in the argument passed in, which is each subdirectory in turn. You might also want to use -mindepth 1 to exclude the current directory: find . -maxdepth 1 -mindepth 1 -type d -exec sh -c '! [ -d "$1/.git" ] && echo "not git repo: $1"' _ {} \; Or, just using bash, enabling dotglob to match hidden directories: (shopt -s dotglob; for d in ./*/; do [[ -d $d/.git ]] || echo "not git repo: $d"; done)
Print all subdirectories in the current directory that do not contain a .git
1,503,604,290,000
So I'm using etckeeper on my machine running Debian 9.1 with KDE and would like to view diffs (or if that isn't yet implemented: past versions) of specific files. How can I do that?
By default, with etckeeper, /etc is a git repository, so you can use git tools to view its contents (and the changes). For example, you can use gitk (after installing it) to browse the repository’s history, and if you want to focus on a specific file, you can specify it on the command line: cd /etc gitk apt/sources.list & Since you’re a KDE user, you might find qgit nicer.
How can I view diffs or at least older versions of specific files with etckeeper?
1,503,604,290,000
I was following through the git documentation and installed Git using source code package. Now, after installing Git, I want to update it (Though it might be unnecessary at this time, I simply want to try and make sure it works). I ran the command git clone git://git.kernel.org/pub/scm/git/git.git and it returned error -bash: /usr/bin/git: No such file or directory. Reason might be obvious, since for installing git, I used the command make prefix=/usr/local install which installed Git in /usr/local/bin/git Now, how to fix this? I tried the same git clone command with --git-dir=/usr/local/bin/git which returned the same error -bash: /usr/bin/git: No such file or directory
What does hash say? Did you have a /usr/bin/git previously and then removed it? That would lead to bash: /usr/bin/git: No such file or directory while hash still believes git to be there. The solution in this case would be to either use a new shell. Or for each shell with the old hash, reset it using hash -r.
couldn't update git via git clone comand
1,503,604,290,000
I'm trying to get an output of one function and pass it to other. set -x OUTPUT=$(git diff --name-only --diff-filter=AM develop... | sed 's/.*/"&"/') ./bin/phpcs $OUTPUT My main problem is that the first function returns a list of files and files may contain spaces. So I'm wrapping them in double-quotes, but when I pass it to my other function other single quotes are added. Output: ++ git diff --name-only --diff-filter=AM develop... ++ sed 's/.*/"&"/' + OUTPUT='"test file.php" "testfile.php"' + ./bin/phpcs '"test' 'file.php"' '"testfile.php"' Main end goal to have call equal to: ./bin/phpcs "test file.php" "testfile.php"
Your issue is that you are adding double quotes to the text outputted by git diff. This mangles the pathnames and makes it even harder to correctly parse the file list, especially if any pathname happens to contain quotes. The single quotes that you see in the tracing output is just added by bash to make it easier to see how strings are delimited (e.g. to show that "test, file.php", and "testfile.php" are three separate arguments). Remember that the tracing output of a shell is debugging output meant for giving you a hint of what the shell is doing, and is not generally the actual code run by the shell. To safely use the pathnames that git diff --name-only outputs, consider also using the -z option. This causes git to output the pathnames as a nul-delimited list. You may then use xargs -0 to execute any command on the elements of that list: git diff --name-only -z --diff-filter=AM develop... | xargs -0 ./bin/phpcs You could also read the list of files into an array. For example, in the bash shell: readarray -d '' -t names < <( git diff --name-only -z --diff-filter=AM develop... ) ./bin/phpcs "${names[@]}" This obviously relies on git diff not outputting too many names.
Bash script: Avoid single quotes added to string
1,503,604,290,000
This answer shows how to diff two strings - Using the diff command to compare two strings? I try: diff <( printf '%s\n' "tring1" ) <( printf '%s\n' "string2" ) The output is: 1c1 < tring1 --- > string2 This shows that the two strings are different. I would like to know at which characters the two strings are different, or at least the first character where the difference starts. How can I do it? This is important when comparing long urls. I study other answers based on git diff at diff within a line I try git diff --word-diff --word-diff-regex=. <( printf '%s\n' "tring1" ) <( printf '%s\n' "string2" ) The output is: diff --git a/dev/fd/63 b/dev/fd/62 index 9234a649..b6ce327a 120000 --- a/dev/fd/63 +++ b/dev/fd/62 @@ -1 +1 @@ pipe:[69160538[-6-]{+8+}] I am not sure if I apply git diff correctly and how to interpret the output.
For your specific use-case, store the strings in files, and compare those with git diff: $ echo tring1 > f1 $ echo string2 > f2 $ git diff --word-diff --word-diff-regex=. --no-index f1 f2 diff --git a/f1 b/f2 index e8ae123..d704b3b 100644 --- a/f1 +++ b/f2 @@ -1 +1 @@ {+s+}tring[-1-]{+2+} This shows that the “s” character was added at the start of the string, and that “1” became “2”.
Show differences in strings
1,503,604,290,000
I run git grep for the first time on a large tree (the Linux kernel). This takes a long time to run. If I cancel with ctrl+C before it finishes, often it immediately shows a line it found. Why did git grep not show the line immediately, when it found it? $ rpm -q git git-2.17.2-1.fc28.x86_64
git grep output is buffered by less. (In most cases. It can be changed using various configuration options, if you need to). The reason I did not notice this, is that git grep does not show the less pager footer when there is less than one screen of output. However, the output is still buffered. (I can see that less is running, by opening another terminal and running ps -ax).
git grep output is buffered. Why?
1,503,604,290,000
I'd like to keep my keys secure, but also not have to enter a passphrase on every single git invocation, when I want to run several commands in quick succession. I've researched this, and found that ssh-agent/keychain/etc. go too far convenience-vs-security-wise to my liking. Something like xyz git pull would be perfect, where xyz checks if my key is decrypted, and if it isn't - asks for my passphrase, and then after N minutes of not invoking xyz it forgets the decrypted value. Exactly like sudo. Does this exist / can this be achieved through some tricky means? There's a similar question about this, but our use cases differ.
This is exactly what ssh-agent does. where xyz checks if my key is decrypted, and if it isn't - asks for my passphrase You don't need any xyz. Just start ssh-agent at the start of your session (for example in ~/.bashrc): [ -z "$SSH_AUTH_SOCK" ] && eval $(ssh-agent -t 5m) And configure your ssh client to add the keys when they are first used by setting AddKeysToAgent yes in your ~/.ssh/config. and then after N minutes of not invoking xyz it forgets the decrypted value. This is what the -t switch of the ssh-agent does. Sets default timeout for added keys (in the example above 5 minutes).
Sudo-like utility for ssh, or at least git in particular?
1,503,604,290,000
I accidentally typed git init in my home directory which caused git to start tracking everything in my home directory and I need to remove it. Is there a git command or a way to terminate git tracking everything in my home directory? Thanks.
Git creates a folder .git in the top-level directory it tracks. The only thing you need to do is to remove that folder using rm -Rf .git.
Terminating Git
1,503,604,290,000
If I have a local ikiwiki on my laptop I need a "repository" directory (mywiki.git - a bare repository), a "scrdir" (myiki a git repository) and a place where the produced html files go ("destdir") to run it properly from a web browser locally. However if I also want to work with a text editor and git on the command line I need to setup a third git repository say mywiki.local ("working clone"). Which puhes to mywiki.git which in turn triggers a post-update hook to push to the scrdir and rebuild the html pages, as illustrated in the following picture: With this approach, I need three almost identical directories on my laptop just to run one wiki, i.e. it occupies three times the disk space instead of just once. What is the reason behind this? Is there a safe way to circumvent this if you are just working on one machine, to reduce it to just two or even better one directory?
I have successfully used ikiwiki with 0+ repositories. 0..2 are single-user, so I have not run into conflicts (yet). 0..1 were just an experiment with ikiwiki. Here is what I tried: 0 repositories - compiling manually, 1 repository (working directory == srcdir) without upstream - compiling manually, 2 repositories (working directory == srcdir + upstream) 3+ repositories (the above 2 on server + remote on a NB) With 3+ we are going multiuser, so I expect it is going to be more interesting. I was seeking an answer to same question as yours, so here is the answer: If you are directly editing ikiwiki srcdir you will run into a conflict if the same file is edited by web-ui (or pushed to bare repo by other users). If you commit in srcdir, conflict will be handled by web-ui. But any uncommitted changes to the file will be lost. If you are not using web editing feature, and there are no other users committing to the repo, you are fine with 2 repos. And even 1 might work. Or 1 with remote repository. Also I guess it would be easy to write a plugin to stash any changes before srcdir is updated/reset.
Why do I need 3 git repositories for ikiwiki if I want to commit locally
1,503,604,290,000
I was trying to set up a git server. I set up the SSH server successfully, and now I was trying to set up an anonymous git service, but it's not working properly. I copied the sample systemd service file from the git book https://git-scm.com/book/en/v2/Git-on-the-Server-Git-Daemon, changing only the paths to where I have the files: $ cat /etc/systemd/system/git-daemon.service [Unit] Description=Start Git Daemon [Service] ExecStart=/usr/bin/git daemon --reuseaddr --base-path=/srv /srv/src/ Restart=always RestartSec=500ms StandardOutput=syslog StandardError=syslog SyslogIdentifier=git-daemon User=git Group=git [Install] WantedBy=multi-user.target Then created a git user and group: $ sudo useradd -U --system git $ sudo usermod -d /nonexistent git $ sudo usermod -s /usr/sbin/nologin git $ sudo usermod -c git git $ getent passwd git git:x:998:998:git:/nonexistent:/usr/sbin/nologin $ groups git git : git Then enabled and started the service (which I'll show below that is active and running): $ sudo systemctl enable git-daemon.service Created symlink /etc/systemd/system/multi-user.target.wants/git-daemon.service ��� /etc/systemd/system/git-daemon.service. $ sudo systemctl start git-daemon.service Then created the file to export the repo: $ touch /srv/src/alx/libalx.git/git-daemon-export-ok $ ls -l /srv/src/alx/libalx.git/git-daemon-export-ok -rw-r--r-- 1 alx alx 0 Jan 7 18:49 /srv/src/alx/libalx.git/git-daemon-export-ok And then attempted to clone from it: $ git clone git://localhost/src/alx/libalx.git Cloning into 'libalx'... fatal: remote error: access denied or repository not exported: /src/alx/libalx.git The service complains that it's not whitelisted (but it is, isn't it?): $ sudo systemctl status git-daemon.service ��� git-daemon.service - Start Git Daemon Loaded: loaded (/etc/systemd/system/git-daemon.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2022-01-07 18:43:52 CET; 24min ago Main PID: 43138 (git) Tasks: 2 (limit: 3366) Memory: 528.0K CPU: 26ms CGroup: /system.slice/git-daemon.service ������43138 /usr/bin/git daemon --reuseaddr --base-path=/srv /srv/src/ ������43139 /usr/lib/git-core/git-daemon --reuseaddr --base-path=/srv /srv/src/ Jan 07 18:43:52 rpi systemd[1]: Started Start Git Daemon. Jan 07 18:43:59 rpi git-daemon[43144]: [43144] '/srv/src/alx/libalx.git': not in whitelist Jan 07 18:50:02 rpi git-daemon[43175]: [43175] '/srv/src/alx/libalx.git': not in whitelist Jan 07 18:50:03 rpi git-daemon[43176]: [43176] '/srv/src/alx/libalx.git': not in whitelist Jan 07 18:52:54 rpi git-daemon[43186]: [43186] '/srv/src/alx/libalx.git': not in whitelist Why am I not able to clone via git://? If I pass a completely invalid path to clone I get the same exact output at client side, but at server side the log is different: $ git clone git://localhost/src/ald/sdf/sdf.git Cloning into 'sdf'... fatal: remote error: access denied or repository not exported: /src/ald/sdf/sdf.git $ sudo systemctl status git-daemon.service ... Jan 07 19:13:37 rpi git-daemon[43261]: [43261] '/srv/src/ald/sdf/sdf.git' does not appear to be a git repository
Just encountered this myself a few minutes ago and came across your question in the process of figuring it out. Remove the trailing slash from the directory path at the end of your git daemon command in your systemd file. This seems to cause an issue with the whitelist as seen in the error shown in /var/log/syslog. ExecStart=/usr/bin/git daemon --reuseaddr --base-path=/srv /srv/src After I made a similar change I was able to use the git protocol as expected.
git-daemon says 'not in whitelist' even if git-daemon-export-ok exists
1,503,604,290,000
What happens if two git pull command are run simultaneously in the same directory?
git does file locking to prevent corrupting the repository. You may get messages like error: cannot lock ref 'refs/remotes/origin/develop': is at 2cfbc5fed0c5d461740708db3f0e21e5a81b87f9 but expected 36c438af7c374e5d131240f9817dabb27d2e0a2c From github.com:myrepository ! 36c438a..2cfbc5f develop -> origin/develop (unable to update local ref) error: cannot lock ref 'refs/remotes/origin/master': is at b9a3f6cf9dafc30df38542e5e51ae4842c50814d but expected 5e6174b3c7071c840effeda6c708d6aef36f7c6a ! 5e6174b..b9a3f6c master -> origin/master (unable to update local ref) from the git processes that fail to get the lock. That is all. If the two git pull processes are slightly out of sync with each other, the effect will be the same as running the command twice.
Running two git commands in parallel
1,503,604,290,000
A common problem game developers have with the Unity3D engine and Git is that Unity and Git fight for whether an empty directory should exist or not - Git doesn't care, Unity3D will keep making git trackable *.meta files for empty directories. Basically means devs have to manually find and delete directories and meta files if a commit is made removing files and directories. I'd like to create a Git post-checkout hook to trigger a directory removal when Git deletes files. I have made a good start on it - I know what I need Git to do. But I'm not great with shell scripting and I'm struggling to make it work efficiently and correctly. The main issue I'm having is that I just cannot get this line right: dirs_to_check="($changed_files | xargs dirname | xargs sort -u)" I was hoping it'd pipe each line into dirname, then take the whole list and remove dupes. #!/bin/sh # This script will be run by Git after a checkout. # --- Command line oldRev="$1" newRev="$2" isBranchCheckout="$3" # Grab a list of deleted files: changed_files="$(git diff-tree -r --name-only --diff-filter=D --no-commit-id $oldRev $newRev)" # Just testing: ##changed_files="$(git diff-tree -r --name-only --no-commit-id f5865290 eb793b0c)" # Early exit if there are no removed files at all: if [ -z "$changed_files" ]; then echo "No empty dirs" exit 0 fi echo "$changed_files" # Get the list of dir paths and then sort and remove dupes: dirs_to_check="($changed_files | xargs dirname | xargs sort -u)" # For each dir check if its empty and if so, remove it: # TODO: What about the case where the parent dir is also empty of files? for dir in $dirs_to_check; do if [ "$(ls -A $dir)" ]; then echo "$dir Not Empty" else echo "$dir Empty" rm $dir fi done Here is some sample changed_files text if you want to test more easily: test/with dir spaces/debrief/css/style.css WFTO/uiresources/wftoUI/debrief/debrief.html WFTO/uiresources/wftoUI/debrief/debrief_specification.js WFTO/uiresources/wftoUI/debrief/js/debrief.js WFTO/uiresources/wftoUI/debrief/js/debrief_specification.js WFTO/uiresources/wftoUI/loading/Loading.css WFTO/uiresources/wftoUI/loading/Loading.html WFTO/uiresources/wftoUI/loading/LoadingDLC1.html WFTO/uiresources/wftoUI/loading/images/HoG-logo.png WFTO/uiresources/wftoUI/loading/images/background_unused.jpg WFTO/uiresources/wftoUI/loading/images/banner-patch-1_4.png WFTO/uiresources/wftoUI/loading/images/bg-back.jpg WFTO/uiresources/wftoUI/loading/images/bg-front_unused.jpg WFTO/uiresources/wftoUI/loading/images/bg-front_unused.png WFTO/uiresources/wftoUI/loading/images/bg-logo.png WFTO/uiresources/wftoUI/loading/images/dlc1/bg-back.jpg WFTO/uiresources/wftoUI/loading/images/dlc1/bg-logo.png WFTO/uiresources/wftoUI/loading/images/dlc1/load-bar-empty.png WFTO/uiresources/wftoUI/loading/images/dlc1/load-bar-full.png WFTO/uiresources/wftoUI/loading/images/load-bar-empty.png WFTO/uiresources/wftoUI/loading/images/load-bar-full.png WFTO/uiresources/wftoUI/loading/images/loading-background.png WFTO/uiresources/wftoUI/loading/images/loading-background_unused.jpg WFTO/uiresources/wftoUI/loading/images/random_loading_pics/Ld0.png WFTO/uiresources/wftoUI/loading/images/random_loading_pics/Ld1.png WFTO/uiresources/wftoUI/loading/images/random_loading_pics/Ld10.png
You probably meant dirs_to_check="$(echo "$changed_files" | xargs dirname | sort -u)" A simple solution, unless you have thousands of directories, is simply to try to rmdir each directory and ignore the errors. find . -depth -type d -exec echo rmdir --ignore-fail-on-non-empty {} + Change . to the top of the directories concerned. If your rmdir doesnt have the ignore option just redirect 2>/dev/null to not have the warnings.
Detect and remove empty directories from list
1,503,604,290,000
I'm getting a 'permission denied' error on a git alias. It works with root but not my user account: $ andy@ubuntu:/usr/local/bin$ sudo git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit" $ andy@ubuntu:/usr/local/bin$ git lg fatal: cannot exec 'git-lg': Permission denied $ andy@ubuntu:/usr/local/bin$ Any Ideas?
There's an entry in your $PATH pointing to a directory that you can't access, and you're using a version of git earlier than 1.7.10.1. When you run git lg git first does some setup, including adding an entry to the copy of the $PATH that it is using. Then it tries to run the command git-lg, so that a command would override the alias. When it does that it's getting the permission denied error shown in your output. Older versions of git would stop at that point. Starting with version 1.7.10.1, it will treat that error the same as the command just not being found. When you ran that as root git was able to look through all of the directories in the $PATH, see that no git-lg command exists, and so it would go on to use the defined alias. To fix the problem you can upgrade to a newer version of git. The other option would be to make sure that you have permission to access all directories listed in your $PATH, either by granting additional permissions on any that are a problem or by not including those in the list.
Git Alias 'Permission Denied'
1,503,604,290,000
I sometimes use characters such as ! and $ in commit messages, they need to be manually escaped, but not if you use single quotes like this git commit -m 'My $message here!'. I tried to write a function to make gc and all text following as the message, but no luck in making it use single quotes. Everything I've tried, it still seems to use double-quotes in the end, making the $message part hidden, and ! won't work either. I've tried this: gc() { git commit -m ''$*'' } Also this: gc() { message="$*" git commit -m ''$message'' } Tried other things too that didn't work, when checking git log words starting with $ are not shown in the message. It works with single quotes, but it's using double anyway. I want to run gc My $message here all text after gc should be the message, I can't force it to use single quotes, it ends up double. It would output My here only. Is there a way to write this function so it would work the way I want? Not sure if this is possible, thanks! If there is you're smarter than Bard, ChatGPT, Claude, and Bing AI, because I asked them all too, for several hours had no luck.
TL,DR: don't. What you're asking for is impossible. When you write gc My $message here, this is an instruction to expand the value of the variable message and use the expansion as part of the arguments of the function. You can do something like what you want by tricking the shell with an alias that adds a comment marker and calls a function that reads the comment from the shell history. This allows the function to receive arbitrary characters except newlines. setopt interactive_comments alias gc='gc_function #' function gc_function { emulate -LR zsh setopt extended_glob local msg=${history[$HISTCMD]#*[[:space:]]##} git commit -m "$msg" } This is not (and cannot be) fully robust. The version I posted requires a space or other blank character after gc; if you use a different non-word-constituent character, the commit message might not be what you expect. I do not recommend this. You're making it easy to write a one-line commit message, and hard to write a good commit message. A good commit message explains what the commit does and how. A good commit message is written in an editor. If you write one-line commit messages, you're doing it wrong and you will regret it.
Run `git commit -m` with single quotes in zsh
1,503,604,290,000
I'd like to search all git tracked files that 1. has an .hs file extension and 2. contain the word import in any lines. I've tried to use git ls-files -z | xargs -0 rg -g '*.hs' "import" however unfortunately if you pass an explicit list of files to rg it seems to ignore the -g glob flag. I could potentially use grep to use some regex lookbehind to extract files with a specific file extension, or potentially filter the output from git ls-files -z (ensuring we keep the null separated filenames aspect, both approaches seem a bit clunky though... If anyone has any ideas.
I hope I'm not misreading the question. If you want " to search all git tracked files that contain the word import in any lines", that should be: git ls-files -z | xargs -0 grep -l import If you only want to search in *.hs files, then: git ls-files -z '*.hs' | xargs -0 grep -l import
How can I search only git tracked files with a specific file extension?
1,503,604,290,000
I can test if the current directory like this: [[ $(git rev-parse --is-inside-work-tree 2> /dev/null) == true ]] && echo yes ..but how can I do the same for a directory that is not the current working directory?
Just use the -C global option to git. Doing this, and simplifying your code (why would you parse the output to reconstruct information that's directly encoded in the return status?): directory=. # or wherever if git -C "$directory" rev-parse --is-inside-work-tree >/dev/null 2>/dev/null; then echo yes fi
How to check if a directory is in a git working tree when that directory is not the current working directory?
1,503,604,290,000
I am trying to delete some local git branches with git branch -D $(git branch | grep 'RTL-1[1|2|3]' | xargs) However I am getting this kind of error error: branch 'RTL-1114_branch_name1?[m' not found. error: branch 'RTL-1224_branch_name2?[m' not found. error: branch 'RTL-1225_another_branch?[m' not found. For some reason string "?[m" is being added, but without git command I am getting casual print of branches separates by space. I believe it worked on my linux machine, is it different on MacOS?
You’ve probably got git and/or grep configured to always output using colours; in that case, git branch -D $(git branch --color=never | grep --color=never 'RTL-1[123]') should work. You can use git’s own pattern-matching: git branch -D $(git branch --color=never -l '*RTL-1[123]*') To avoid this in future, you should use the auto setting for color: it will output colour when outputting to a terminal, and won’t otherwise. To configure git appropriately: git config --global color.ui auto For grep, check your aliases.
Mac OS xargs adds '?[m' at the end of line
1,503,604,290,000
I'm curious if anyone has a way to automatically generate a different set of --exclude-dir flags for grep for each different codebase that you work in. Because in one project, I'll never want to search in the output/ dir, and in another, I'll never want to search in the checkpoints/ directory. Since there are often a few folders in a codebase that have non-source code, I always have to type those out manually (e.g. grep --exclude_dir {onedir, twodir, threedir} ...) Ideally, for whatever codebase I'm in, I can just have a file in it that grep can look into to see what to automatically populate the --exclude-dir option with whenever I call grep from the command line. So that I don't have to type out a long list of directory names to exclude every time, which differ based on which project I'm currently working in. If it could just read from an existing .gitignore that would work too.
The following script works for me #!/bin/bash if [ -r .grepignore ]; then while read -r line; do if [[ "$line" =~ '#' ]] || [[ "$line" =~ ^$ ]]; then continue fi EXCLUDE="$EXCLUDE --exclude-dir=\"$line\"" done < .grepignore fi eval grep -r "$EXCLUDE" '"$@"' The script checks whether a file .grepignore exists and is readable. If so, it constructs a string EXCLUDE containing --exclude-dir="$line", for any line $line in that file (without leading and trailing whitespace), provided it is not empty or contains a #. The script then passes that EXCLUDE string to grep and also adds arguments you gave to the script. In order to execute the script, save the code in a file mygrep, make it executable with chmod +x /path/to/mygrep, and call it with /path/to/mygrep, followed by any options you would give to grep and of course by the search term.
Have custom grep exclude dirs for each project
1,503,604,290,000
I wrote a ansible role to automate installing etckeeper. I discover that git will complain if I haven't configured user.email. In some circumstances, git commits will fail. This includes automatic commits to etckeeper when installing a package, potentially causing the install to fail. So I have to add a task for that, like everyone else does :). The frustrating thing is that in some circumstances, it seemed to work ok. And it doesn't seem to be a problem when using etckeeper manually. user.email is never mentioned in the tutorial. Is it actually necessary to set user.email in the Ansible role? If so... there must be some deliberate reason(s) causing this. Some explanation, which I could put into a comment in the role, or which would justify a patch to etckeeper or git?
UPDATE: should be fixed in the next release (1.18.8). https://etckeeper.branchable.com/todo/requires___96__user.email__96___be_set_under_undocumented_circumstances/ After hitting this a couple of times, I felt I needed to look at the source code. git absolutely requires an "email address" for its commits. Without one, it will refuse to make a commit. git will "autodetect" an email, if the system hostname can be resolved to a Fully Qualified Domain Name. (You must have at least one . to qualify :). Or, if /etc/mailname exists, it uses that by preference, without checking for .s. etckeeper tries to pass an email address to git, constructed from a username and the system hostname. git will accept such explicitly-specified emails, even if the host part is not an FQDN. If sudo is used, etckeeper uses SUDO_USER from the environment. In case su is used, there is nothing in the environment, and so etckeeper reads the user from the owner of the tty. So git commit and etckeeper vcs commit failed, when I hadn't set user.email, AND my hostname did not resolve to an FQDN. etckeeper commit works in some situations that git commit doesn't. I believe I got confused between these two when I was testing before (among other things). If you run etckeeper from sudo, it won't fail. If you run it from su, it won't fail. It won't fail either if you log in as root and run it; it will find a tty which is owned by root, and pass an email of root@HOSTNAME. etckeeper commit will fail if and only if user.email is not set in git, AND the system hostname cannot be resolved to an FQDN, AND /etc/mailname does not exist (it is created by the Debian exim packages?) AND etckeeper is not run from sudo AND etckeeper is not run from a tty Finally, testing indicated that commands run under ansible are never run from a tty. (Even when using an ssh connection and sudo with a password, where ansible is described as needing to use a pseudo-tty).
ansible role: Why do I have to set user.email in etckeeper?
1,503,604,290,000
I found a lot of ways to deal with the whitespace problem in Git, but all of them require some sort of action on the user side: configure Git to ignore ws changes, setup a pre-commit hook with warning, or just configure the editor to remove them automatically. But is there a way to simply ignore whitespace changes on the server side or even better to strip all whitespace silently? Background: we have a large repository with a number of developers whom we do not want to chase and convince to reconfigure their tools, but we do not want to have any trailing whitespace in our repository. For me the solution is obvious: strip all whitespace once, and ignore any ws changes from that point on. Ideally, also strip ws in all new commits. But how can I do this?
You can't really do this sanely. You can't modify the content of a commit; you can only create new commits. Even if this were possible, it would break git: the commits on the server would be unrelated to the history stored in local developer repositories, and nothing would ever work. You really need to perform this sort of filtering before files are added to the repository, which is why you do it client side in pre-commit hooks, etc. A better solution is to implement an enforcement mechanism on the server: reject changes that don't meet your standards.
Git Server: ignore whitespace changes in new commits
1,503,604,290,000
I am working on the atom-editor-git PKGBUILD in the AUR, hoping to turn it into an Atom equivalent to the gvim-git PKGBUILD. See the gvim-git PKGBUILD updates its package version whenever it is run to the latest release of gVim, e.g., if I was to run it right now it would build a package for gVim 7.4.1236. The atom-editor-git PKGBUILD, however, returns the package version 1.4.0.r653.g41029f6 when 1.4.2 is the latest release of Atom. gvim-git uses this pkgver() function: pkgver() { cd $_pkgname git describe --tags | sed 's/^v//;s/-/./g' } while atom-editor-git uses: pkgver() { cd "$srcdir/atom" git describe --long --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//' } the obvious solution would be to replace git describe --long --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//' with git describe --tags | sed 's/^v//;s/-/./g' in the atom-editor-git PKGBUILD, but running git describe --tags | sed 's/^v//;s/-/./g' in the Atom git repository gives: 1.4.0.653.g41029f6 which is not in the format I want (1.4.2), so I suspect that what I need to get atom-editor-git to package the latest release of Atom is an alternative git line in the pkgver() function and that is what I am here for. To be clear, I want pkgver() to give me 1.4.2 exactly for the current version, not v1.4.2 or v1.4.2-1-<COMMIT> where <COMMIT> is the 7-character commit short-descriptor.
Atom uses the stable branch for its stable release builds, so to find the latest tag for a release you need to check that branch: $ git describe --tags stable v1.4.2-1-ge9db64c To retrieve the corresponding tag, keep everything up to the first -: $ git describe --tags stable | cut -d- -f1 v1.4.2 To get the version without the leading v, strip that off: $ git describe --tags stable | cut -d- -f1 | sed 's/^v//' 1.4.2
How do I get git to give me an acceptable pkgver for Atom which I can use to check it out?
1,428,000,262,000
I've downloaded the latest kernel sources: git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git cd linux-stable git tag -l | less and picked v3.9.1. git checkout -b v3.9.1 git branch --set-upstream v3.9.1 origin/master , pulled the distribution: git pull and ran: make kernelversion which always outputs: 4.0.0-rc5 , an unstable version. How may I download v3.9.1(a stable version)?
When you run git branch --set-upstream v3.9.1 origin/master you're telling git that you want your local v3.9.1 branch to track master on the remote. To get the remote v3.9.1 you can simply do git checkout v3.9.1 If you're using the repository you created previously, you'll need to delete your own v3.9.1 branch first: git checkout master git branch -d v3.9.1 git checkout v3.9.1 will put you in detached HEAD state, at the commit tagged v3.9.1 on the remote (v3.9.1 is a tag on the remote, not a branch). Once you're there you can create a local v3.9.1 branch if you wish by running git checkout -b v3.9.1 But whether or not you create a local branch, at this point make kernelversion should output 3.9.1 As Devon points out you can do this in one shot when cloning the tree initially: git clone -b v3.9.1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git This works even though v3.9.1 is a tag, and you end up in detached HEAD state as above.
How to select the tag of the latest non-unstable/release candidate version?
1,428,000,262,000
I want to write a script that will run git diff --name-status master..<BRANCH> but when I run this: for i in $(git branch | grep -v master); do echo $i; done I get echo one directory because git branch echo asterisk (I have one directory in current directory) * <SELECTED BRANCH> Why * is expanded and how can I prevent that expansion? UPDATE: I can prevent this by using this: for i in $(git branch | tr -d '*' | grep -v master); done; But why is this happening? Why I need to remove asterisk?
Unquoted variables and command substitutions like $i or $(git …) apply the split+glob operator to the string result. That is: Build a string containing the value of the variable or the output of the command (minus final newlines in the latter case). Split the string into separate fields according to the value of IFS. Interpret each field as a wildcard pattern and replace it by the list of matching file names; if a pattern doesn't match any file, leave it intact. The output of git branch | grep -v master (step 1) contains * master which is split (step 2) into two fields * and master; * is replaced (step 3) by the list of file names in the current directory. You can run set -f to temporarily disable globbing. Another approach is to avoid command substitution and instead parse the input with read. Neither do the right thing though — you'll have spurious branch names, because the git output contains more than what you need (the * flag to indicate the current branch, but also things like remotes/somewhere/foo -> bar for remote-tracking branches). I think the following is safe if inelegant: for i in $(git branch | sed -e 's/^..//' -e 's/ .*//'); do echo $i done I think the robust way is to use git-for-each-ref. for i in $(git for-each-ref --format='%(refname:short)' refs/heads refs/remotes); do echo $i done
Why asterisk in command result in for loop is expanding?
1,428,000,262,000
I want compress all the git repositories on my computer (say in ~). I.e., for each directory {}, that contains directory or file (in case of submodules) named .git, I want to execute git gc --aggressive --git-dir={}. I tried the following: /bin/find /c/libs/boost/ -name '.git' -print -exec git --git-dir=dirname {} gc --aggressive \; but output consist of plenty of fatal: Not a git repository: 'dirname /c/libs/boost/.git' etc. What should I do to use dirname command correctly? Or something else to achieve desired effect?
You're passing the word dirname as the argument to --git-dir. With GNU or FreeBSD find, the -execdir action executes a command in the directory containing the matching file. find /c/libs/boost/ -name '.git' -execdir git gc --aggressive \; If your find command doesn't have -execdir, you can pass the .git directory as an argument to --git-dir. find /c/libs/boost/ -name '.git' -exec git --git-dir {} gc --aggressive \; In general, if you need shell expansion, invoke a shell explicitly, with sh -c 'shell command'. Don't attempt to perform any interpolation in the shell command, as that would fail with file names containing special characters. Pass the match(es) as an argument to the shell script. Note that after sh -c 'shell command', the first argument is $0, and the other arguments ($1, $2, …) collectively form "$@". find /c/libs/boost/ -name '.git' -exec sh -c 'cd "${0%/.}" && git gc --aggressive' {} \; find /c/libs/boost/ -name '.git' -exec sh -c 'for dir; do cd "${dir%/.}" && git gc --aggressive' _ {} +
apply specific command for each git repository
1,428,000,262,000
I have some repos which are both in SVN and Git. My username is guyfawkes, and in my home directory I have folder www which contains all my repos. In this directory I also have file update.sh: [guyfawkes@guyfawkes-desktop ~/www]$ cat update.sh cd /home/guyfawkes/www cd crm echo "upd crm" svn up echo "update crm completed" echo "-------" cd ../crm_sql echo "upd sql" svn up echo "update sql completed" echo "-------" cd ../crm_old echo "upd old" svn up echo "update old completed" echo "-------" cd ../mysqldiff echo "upd mysqldiff" git pull sotmarket master echo "update mysqlidff completed" git push origin master echo "push to github completed" echo "-------" cd ../mysql-migration-manager echo "upd mmmm" git pull echo "mmm updated" cd data echo "upd data" git pull echo "data updated" My crontab is: [guyfawkes@guyfawkes-desktop ~/www]$ crontab -l */5 * * * * /home/guyfawkes/www/update.sh So, it works perfectly with svn repos, but I have this mails in /var/spool/mail/guyfawkes (from cron): X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/home/guyfawkes> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=guyfawkes> X-Cron-Env: <USER=guyfawkes> upd crm Fetching external item into 'public/old' External at revision 32674. At revision 483. update crm completed ------- upd sql At revision 29. update sql completed ------- upd old At revision 32674. update old completed ------- upd mysqldiff Permission denied (publickey,keyboard-interactive). fatal: The remote end hung up unexpectedly update mysqlidff completed Permission denied (publickey). fatal: The remote end hung up unexpectedly push to github completed ------- upd mmmm Permission denied (publickey,keyboard-interactive). fatal: The remote end hung up unexpectedly mmm updated upd data Permission denied (publickey,keyboard-interactive). fatal: The remote end hung up unexpectedly data updated How can I to fix it?
The problem is you are trying to update from github which requires an ssh key. Either create a dedicated ssh key without a password on your server and add it to your github account or use the http-readonly uri to update your repository: git pull --mirror https://github.com/account/repository.git
Crontab with SVN and Git
1,428,000,262,000
I'm using a bash script to create a Git hook. I want to run a process (linting) against files I'm committing. I only want to run the process if the files actually exist (in other words, not consider files taht were deleted from in my commit). I tried this CHANGED_FILES=$(git diff --cached --name-only | grep ".js$") echo "$CHANGED_FILES" if [ -n "$CHANGED_FILES" ]; then REAL_FILES=() for pathname in "${CHANGED_FILES[@]}"; do if [ -e "$pathname" ]; then REAL_FILES+=( "$pathname" ) fi done echo "real files are ..." echo "$REAL_FILES" but the above only works if there is a single file changed. If there are two or more files changed, nothing happens and my output just looks like src/app/test1.js src/app/test2.js real files are ... So nothign is getting saved for "REAL_FILES" when the CHANGED_FILES array contains 2 or more files that actually exist. How can I fix the above?
The problem with your script is that CHANGED_FILES is a scalar variable, not an array. Try: CHANGED_FILES=( $(git diff --cached --name-only | grep ".js$") ) i.e. add parentheses around the $(git...) command substitution. Note that this is subject to the usual shell word splitting, so if there is any chance(*) that there might be spaces/newlines/shell metacharacters in any of the pathnames, you should use mapfile and process substitution instead of command substitution, with the -z option for NUL separators with both git diff and grep. For example: mapfile -d '' -t CHANGED_FILES < \ <(git diff -z --cached --name-only | grep -z '\.js$') BTW, mapfile and readarray are synonyms in bash. See help mapfile for details. In ksh, it's readarray only and mapfile doesn't exist. (*) there is always a chance for this because those characters are valid filename characters on unix filesystems. The only character which isn't valid in a pathname is NUL (and the only characters not valid in the filename portion of a pathname are / and NUL). So, you should always write your scripts defensively and assume that there will always be at least one such annoying filename somewhere. i.e. always use the mapfile version. BTW, if you want to print ALL elements of the $REAL_FILES array (instead of just the first element), then use the [@] subscript OR use declare -p / typeset -p (which is better for debugging. and for generating output which can be executed in bash without quoting/whitespace problems). e.g. instead of this: echo "$REAL_FILES" do this: echo "${REAL_FILES[@]}" or this: typeset -p REAL_FILES (declare vs typeset is another bash vs ksh discrepancy. ksh had readarray and typeset, then bash copied them from ksh and renamed them to mapfile and declare and added the ksh versions as aliases for them. I don't know why)
In bash, how do I create an array of committed files that still exist on my file system?
1,428,000,262,000
With the big move from master as the default branch name for git in many projects (e.g. to main in GitHub), some of the scripts and configurations assuming it as the default name will be broken. For example, if you have setup aliases to save time typing some of the git commands: [alias] com = checkout master rbm = rebase master rbmi = rebase -i master The same applies to shell scripts - is there any equivalent to git checkout master but where master would be any default branch of the current repository?
Git doesn't have a concept of a default branch. A repository may contain many independent lines of development (e.g., a maintenance and a development branch), none of which are more special than any other. The importance of branches and how they're to be merged is up to the owner of the repository. What you think of as the default branch, on GitHub and elsewhere, is the branch to which HEAD points in a bare repository. You can see what that name was for a remote when you last updated it by running this: $ git rev-parse --abbrev-ref origin/HEAD origin/master If you want to know the very latest value from the remote and are willing to make a network request to do it, then you can do this: $ git ls-remote --symref origin | head -n1 ref: refs/heads/master HEAD Note that this reference is not updated automatically; you must run git remote set-head -a origin to update it. However, that doesn't tell you the name of the local branch that you're using as the default branch. For example, the command above is from my copy of Git, where the default branch is master. However, on my local machine, the branch into which the remote repository's default branch is pulled is called dev (that's my preferred default branch name). If that's what you want to know, then this is probably the command you want (assuming origin is your remote): $ git config -l | ruby -e ' remote = ARGV[0] head = `git rev-parse --abbrev-ref #{remote}/HEAD`.chomp a = {} while line = $stdin.gets if line =~ /^branch\.(.*)\.remote=(.*)$/ a[$1] ||= [nil, nil] a[$1][0] = $2 elsif line =~ %r[^branch\.(.*)\.merge=refs/heads/(.*)$] a[$1] ||= [nil, nil] a[$1][1] = $2 end end puts a.map { |k, (a, b)| ["#{a}/#{b}", k]}.to_h[head]' origin Since this is Ruby, if you want make it a one-liner, you can put semicolons in place of the newlines. You can also use Perl if you like that better.
How to operate on default branch within gitconfig and shell scripts
1,428,000,262,000
I am about to try and install the git package. In Synaptic, in the dependencies tab, it writes: Breaks: bash-completion (<1:1.9-1) Breaks: bash-completion [italicized] I have the latest version of bash-completion offered by the repository installed (version 1:2.8-1ubuntu1). I have read that git comes with some adapted auto-completion features, and I guess that this feature won't actually prevent completion to work in bash, right? Also, the apt-get -s install git command doesn't output anything regarding the bash-completion package. So my questions are: Since I already have the latest version of the bash-completion package installed, what will happen to it upon the particular case of installing git? What does the second line in italic mean in this particular context? How are the two lines different and not merged in a single 'Breaks: bash-completion' line? Edit (additional information) I have Linux Mint 19.1 (Ubuntu 18.04 base) The repository offers git 1:2.17.1-1ubuntu0.4
You're seeing this Synaptic bug, which causes it to misparse “Breaks” dependencies. The two packages aren't actually incompatible. You should be able to install git with some other tool, for example sudo apt-get install git in a terminal. It won't have any impact on the bash-completion package. I can confirm that there's no problem installing the git and bash-completion packages together at least on Ubuntu 16.04 and 18.04, and that does allow bash to complete git commands intelligently. The git package is incompatible with an old version of the bash-completion package, so it declares a dependency Breaks: bash-completion (<< 1:1.90-1), meaning that this git package is incompatible with any version of bash-completion that's older than 1:1.90-1. This is an ancient version that is not present in any currently-supported version of Ubuntu: the oldest supported version (xenial) has 1:2.1-4.2ubuntu1. The reason for the incompatibility is that the git package provides its own script file for bash completion and the structure of bash completion scripts was different in older versions of bash-completion.
Git package breaks bash-completion?
1,428,000,262,000
Currently I have this and it works as expected if I use it like addcommit 'test commit' but if I use it as addcommit test commit it only sees the first word test. Ideally I'd like to have the functionality of addcommit test commit and it executing git add . && git commit -m 'test commit' addcommit() { git add . && git commit -m "$1" } PS. I don't understand how the "$1" works in this case, maybe that would be a good starting point to understanding how this should work.
Replace "$1" with "$*". And in order to be completely safe against IFS traps: addcommit() { local IFS=' ' git add . && git commit -m "$*" } This is a case where an alias could help, and allow the commit message to contain any character: alias addcommit='_m=$(fc -nl -0); git add . && git commit -m "${_m#*addcommit }" #' addcommit $foo * $bar # will use the literal "$foo * $bar" message, without expanding it (works in bash and ksh93)
bashrc function, git commit -m with spaces
1,428,000,262,000
I have been working a local repository synced with a GitHub repository. Recently our GitHub repository has a newly created branch release. Locally, I first run git checkout release, which seems successful, and says: Branch release set up to track remote branch release from origin. Switched to a new branch 'release' I heard that when release doesn't exist locally, git checkout release will pull from a branch also named the same as release from repository origin. So I think running git pull isn't necessary. But to my surprise, when I run git pull, it tells me that # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. # # Lines starting with '#' will be ignored, and an empty message aborts # the commit. Why does git pull tell me it will merge? What is the reason for the merge? What shall i do then?
A merge on git pull indicates that the local and remote branches have diverged. That means that there are new commits in both branches (local and remote) since the last time they were in sync. To integrate the new remote commits into your local branch without a new merge commit, kill your current git command, then run git merge --abort to abort the merge. Then run git rebase origin/release to rebase your local commits on top of the new remote commits. git pull -r will avoid this in the future (it instructs git pull to rebase instead of merging).
After checkout a new remote branch, why does pull tells me that it will merge?
1,428,000,262,000
When I run find -maxdepth 1 -type d -name 'iptp*' -execdir bash -c "ls {}" \; I get a listing of all dirs named iptp* When I run find -maxdepth 1 -type d -name 'iptp*' -execdir bash -c "git status {}" \; I get fatal: Not a git repository (or any parent up to mount parent ) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). I seems like git status is run in the parent dir where find was started. What do I make wrong?
With -execdir, the command is run in the directory containing the match, i.e. the parent directory of the directory whose name starts with “iptp”. You could instead look for .git with a path matching iptp*: find -maxdepth 2 -type -d -name .git -path "*/iptp*/*" -execdir git status \;
find dir with wildcard and run git status not working
1,428,000,262,000
I am using a script to update my system: cd /opt/ chmod 600 /opt/updater/.ssh/.pk ssh-agent bash -c 'ssh-add /opt/updater/.ssh/.pk; git stash; git pull origin master' /opt/updater/bin/updater.sh My problem is that if /opt/updater/.ssh/.pk us not readable or the ssh-key was changed, the process will get stuck like this: ssh-agent bash -c 'ssh-add /opt/RDE/rdeupdater/.ssh/.pk; git stash; git pull origin master;EX=$?;echo "-$EX" ' /opt/RDE/rdeupdater/.ssh/.pk: No such file or directory No local changes to save user@git's password: How can I solve this from getting stuck? Expect isn't allowed on this system.
The trick is to have ssh immediately fail if it tries to do password authentication (thus always only do public/private key authentication). You could set the environment variable GIT_SSH to a shell script to extend the normal ssh command to include -o "PasswordAuthentication no", but if you don't normally access the server where the gitrepository is located, you can also set in ~/.ssh_config: Host server_with_remote_git_repo_name PasswordAuthentication no and then override that if you ever need to access server_with_remote_git_repo_name with a password, by doing ssh -o "PasswordAuthentication yes" server_with_remote_git_repo_name
ssh-agent and timeout
1,428,000,262,000
I am trying to create a personal sync system for my project. I don't want to use something like dropbox, bittorrent sync, owncloud etc for various reasons. At the moment, I have my computers setup to use encfs and git over a usb drive. Where I have a local unencrypted folder on each computer and the encrypted encfs files are on the usb drive. This seems to work fine. What I am worried about is when the usb drive fails. I basically want to automatically keep a backup of the encrypted files on each computer. How do I go about doing that? Ideally, create a backup of the encrypted files when the usb drive is connected, or every minute or hour while the usb drive is connected? If something better is possible, please let me know. Can I use something like rsync with a cron job to do this? What I don't need is the advanced features of rsync to create a time-line of backups. I just need a copy of the latest files on the usb drive.
For backing up files between two computers, rysnc is usually the way to go. If the files may be changed on either computer, unison might be a better way to go. You can run either regularly via a cron job or manually when needed (more robust for unison). Of course you will have to set up a password-less ssh login to the target machine first. If you want to sync to a usb device when it is plugged in, you can always create a udev rule (if that's what your system uses) which runs a script to mount the device and do an rsync every time it is plugged in. If doing this, be sure that it doesn't conflict with any other automatic mounting system that may pick the device up. To do this you would first find out the udev properties of the device as follows: udevadm info --name=/path/to/device --query=property Then you would put a .rules file in /etc/udev/rules.d (depending on system) containing something like this: ENV{ID_SERIAL}=="device_id_serial", ACTION=="add", RUN+="/path/to/script" Where device_id_serial is the ID_SERIAL for your device. Note this is only a very rough outline of what you can do, I have not tested the above (add may not be the correct action). You can always ask another question on any of the above if you are stuck.
Automatically backup usb drive to computer
1,428,000,262,000
When using Git VCS, I execute all of the git commands on the directory that contains a .git repository. I want to execute a git-pull through an SSH trigger but how do I define the path to the repository to perform the action on?
If you set the GIT_DIR environment variable, git will use it as a path to the repository. In general, you can start a subshell like this: (cd /some/other/directory/; git pull) The subshell will have its own current directory and environment variables.
Execute a command in a different path
1,428,000,262,000
I noticed that in git version 1.8.3.1 (provided by CentOS 7) it seems this command is not working: git cat-file -t -- "5378198ea7a83f5fa9bb3ba17f51be3a6ffbecc1:README.md" (Obviously specify a correct git hash and an existing file at that revision) This is the standard error: usage: git cat-file (-t|-s|-e|-p|<type>|--textconv) <object> or: git cat-file (--batch|--batch-check) < <list_of_objects> <type> can be one of: blob, tree, commit, tag -t show object type -s show object size -e exit with zero when there's no error -p pretty-print object's content --textconv for blob objects, run textconv on object's content --batch show info and content of objects fed from the standard input --batch-check show info about objects fed from the standard input To me, it seems that the problem is the "--" escape parameter that is interpreted as a type instead of an escape for consecutive arguments. In fact, this works to me: git cat-file -t "5378198ea7a83f5fa9bb3ba17f51be3a6ffbecc1:README.md" It exists with 0 with this result: blob So, in short. Question How do you suggest to proceed to discover when the "--" parameter was introduced in git? Related documents: https://git-scm.com/docs/git-cat-file (I don't see details) https://stackoverflow.com/questions/22750028/in-git-what-does-dash-dash-mean (no version/time details) https://github.com/git-lfs/git-lfs/issues/1072 (not related to git itself)
git cat-file used to have a strict check on the number of arguments to it, which meant that -- couldn’t be used. The check happened before options were parsed, which is why you get the usage output immediately, with no indication of why the arguments are invalid. This was removed in May 2015; the first release containing this change is 2.5.0. To figure this out, I compared cat-file.c in version 1.8.3.1 to its current state; I noticed the check on argument versions, then looked for the commit which removed it.
git cat-file: when was introduced the "--" escape parameter?
1,428,000,262,000
It's hard to make it clearer than the title. I upgraded from debian 9 to 11 yesterday, and somehow my git package got dumped on the way. So naturally I tried to reinstall it this morning. One problem, it asks me for a dependency that doesn't exist. ~ sudo apt install git 100 err | 10:50:02 Reading package lists... Done Building dependency tree... Done Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: git : Depends: libc6 (>= 2.34) but 2.31-13+deb11u4 is to be installed E: Unable to correct problems, you have held broken packages. ~ sudo apt list libc6 -a 100 err | 10:51:09 Listing... Done libc6/stable,now 2.31-13+deb11u4 amd64 [installed] The libc6 dependency that git is asking makes no sense whatsoever because the one listed on the debian website for my version is 2.28 ( https://packages.debian.org/bullseye/git ). My best guess is that my problem comes from my sources file. Do you think anything is wrong with it? deb http://[debian link]/debian bullseye main deb http://deb[debian link]/debian bullseye-updates main deb http://security[debian link] bullseye-security main Here's the result of apt policy (a little trimmed because I can't post too many links): 100 /var/lib/dpkg/status release a=now 500 http://ppa.launchpad.net/git-core/ppa/ubuntu jammy/main amd64 Packages release v=22.04,o=LP-PPA-git-core,a=jammy,n=jammy,l=Git stable releases,c=main,b=amd64 origin ppa.launchpad.net 500 http://security.[debian link] bullseye-security/main amd64 Packages release v=11,o=Debian,a=stable-security,n=bullseye-security,l=Debian-Security,c=main,b=amd64 origin security.[debian link] 500 http://deb.[debian link]/debian bullseye-updates/main amd64 Packages release v=11-updates,o=Debian,a=stable-updates,n=bullseye-updates,l=Debian,c=main,b=amd64 origin deb.[debian link] 500 http://deb.[debian link]/debian bullseye/main amd64 Packages release v=11.5,o=Debian,a=stable,n=bullseye,l=Debian,c=main,b=amd64 origin deb.[debian link] Pinned packages:```
Your system references the git-core Ubuntu PPA, which is where it’s trying to install git from. Ubuntu PPAs shouldn’t be used with Debian; in this particular case, you’re using a 22.04 PPA which relies on Ubuntu 22.04 packages, including a newer version of libc6 than is available in Debian 11. You can force the installation of git from Debian 11 with sudo apt install -t bullseye git but you should really remove the Ubuntu PPA.
I can't install a package because it asks a dependency version higher than the available one
1,428,000,262,000
I have installed git on Debian 10. Why do I have two identical git binaries in two different places? /usr/lib/git-core/git /usr/bin/git These are identical files, have same sha256sum. But they are not hardlinks. They are same files existing in two copies. Seems strange. I wonder what's the purpose.
This particularity has been upsetting some for years. BTW, you'll read as part of the answer from Jonathan Nieder that upstream does hardlink but Debian does not ship that way since they can't be sure both path are on the same filesystem. ArchLinux faced this problem years ago.
git binaries installed from debian package